C#扩展方法实现

     C#提供了一种机制,可以扩展系统或者第三方类库中的方法。比如说想在string类型的对象里面多一个ToInt32(),来方便的将字符转换成整形。在实现的过程中的关键字为static和this即可。
     下面我们来做一个在string类型中新建一个ToInt32的自定义方法:

public static class Extension//必须先声明一个静态类,类名随意
    {
        public static int ToInt32(this string In)//扩建的方法必须是静态方法,参数里面必须含有this关键字,this关键字后面的类型为需要扩展的类型
        {
            return Convert.ToInt32(In);
        }
    }

      那么在使用string的对象的时候,会多出一个ToInt32的方法。

static void Main(string[] args)
{
       string a = "1";
       int b = a.ToInt32();
       Console.ReadLine();
}

 

      既然可以扩展.net的内置类型,扩展自定义类型也是可以的。

public class A//先定义A类
    {
    }

    public static class Extension//必须先声明一个静态类,类名随意
    {
        public static int ToInt32(this string In)//扩建的方法必须是静态方法,参数里面必须含有this关键字,this关键字后面的类型
        {
            return Convert.ToInt32(In);
        }
        //为A新增一个ExtensionMethod方法
        public static string ExtensionMethod(this A a)//扩建的方法必须是静态方法,参数里面必须含有this关键字,this关键字后面的类型
        {
            return "this is extension method";
        }
    }

     在使用A的对象的时候,会多出一个ExtensionMethod方法:

static void Main(string[] args)
{
      string a = "1";
      int b = a.ToInt32();
      A c = new A();
      string d = c.ExtensionMethod();
      Console.ReadLine();
}

posted @ 2017-02-25 09:24  凌晨三点半  阅读(1181)  评论(0编辑  收藏  举报