前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >扩展方法

扩展方法

作者头像
wfaceboss
发布2019-04-08 11:30:34
6180
发布2019-04-08 11:30:34
举报
文章被收录于专栏:wfacebosswfaceboss

扩展方法被定义为静态方法,但它们是通过实例方法语法进行调用的。 它们的第一个参数指定该方法作用于哪个类型,并且该参数以 this 修饰符为前缀。 扩展方法当然不能破坏面向对象封装的概念,所以只能是访问所扩展类的public成员。

扩展方法使您能够向现有类型“添加”方法,而无需创建新的派生类型、重新编译或以其他方式修改原始类型。扩展方法是一种特殊的静态方法,但可以像扩展类型上的实例方法一样进行调用。

1.this扩展方法 

代码语言:javascript
复制
必须是静态类才可以添加扩展方法     :声明扩展方法的步骤:类必须是static,方法是static

实例1、给string 类型增加一个Add方法,该方法的作用是给字符串增加一个字母a

第一步:声明扩展方法

//声明扩展方法

//扩展方法必须是静态的(是否有参数),Add有三个参数:this 必须有,string表示我要扩展的类型,stringName表示对象名

//三个参数this和扩展的类型必不可少,对象名可以自己随意取如果需要传递参数,再增加一个变量即可

代码语言:javascript
复制
public static  string  Add(this string stringName)//在调用是stringName接受str的值                            this string:表示为string添加一个add方法
        {
            return stringName+"a";
        }
代码语言:javascript
复制
第二步:调用扩展方法,必须用对象来调用   
代码语言:javascript
复制
 Static class Program
       {
        static void Main(string[] args)
        {
            string str = "quzijing";
            //注意调用扩展方法,必须用对象来调用 
            string Newstr = str.Add();
            Console.WriteLine(Newstr);
            Console.ReadKey();
        }
代码语言:javascript
复制

实例2、为string扩展一个验证邮件类

(1)、扩展方法

代码语言:javascript
复制
            
using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Text.RegularExpressions;

 

//声明扩展方法的步骤:类必须是static,方法是static,

//第一个参数是被扩展的对象,前面标注this。

//使用扩展方法的时候必须保证扩展方法类已经在当前代码中using

namespace 扩展方法

{

    //扩展方法必须是静态的

    public static class StringHelper

    {

        //扩展方法必须是静态的,第一个参数必须加上this

        public static bool IsEmail(this string _input)

        {

            return Regex.IsMatch(_input, @"^\\w+@\\w+\\.\\w+$");

        }

        //带多个参数的扩展方法

        //在原始字符串前后加上指定的字符

        public static string Quot(this string _input, string _quot)

        {

            return _quot + _input + _quot;

        }

    }

}

        

(2)、使用方法

代码语言:javascript
复制
            
using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

namespace 扩展方法

{

    class Program

    {

        static void Main(string[] args)

        {

            string _myEmail = "abc@163.com";

            //这里就可以直接使用string类的扩展方法IsEmail了

            Console.WriteLine(_myEmail.IsEmail());

            //调用接收参数的扩展方法

            Console.WriteLine(_myEmail.Quot("!"));

            Console.ReadLine();

        }

    }

}

        
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2017-03-12 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档