C#扩展方法知多少

当咱们想为一个现有的类型添加一个方法的时候,有两种方式:一是直接在现有类型中添加方法;可是不少状况下现有类型都是不容许修改的,那么可使用第二种方式,基于现有类型建立一个子类,而后在子类中添加想要的方法。html

当C# 2.0中出现了静态类以后,对于上面的问题,咱们也能够建立静态工具类来实现想要添加的方法。这样作能够避免建立子类,可是在使用时代码就没有那么直观了。算法

其实,上面的方法都不是很好的解决办法。在C# 3.0中出现了扩展方法,经过扩展方法咱们能够直接在一个现有的类型上"添加"方法。当使用扩展方法的时候,能够像调用实例方法同样的方式来调用扩展方法。编程

扩展方法的使用

扩展方法的建立和使用仍是相对比较简单的。ide

声明扩展方法

相比普通方法,扩展方法有它本身的特征,下面就来看看怎么声明一个扩展方法:工具

  • 它必须在一个非嵌套、非泛型的静态类中(因此扩展方法必定是静态方法)
  • 它至少要有一个参数
  • 第一个参数必须加上this关键字做为前缀,且第一个参数类型也称为扩展类型(extended type),表示该方法对这个类型进行扩展
  • 第一个参数不能用其余任何修饰符(好比out或ref)
  • 第一个参数的类型不能是指针类型
  • 扩展方法的类最好和调用扩展方法的类在同一个命名空间下。或使用using引用。(如:using TestWeb.Common;)

根据上面的要求,咱们给int类型添加了一个扩展方法,用来判断一个int值是否是偶数:post

复制代码
namespace ExtentionMethodTest
{
    public static class ExtentionMethods
    {
        public static bool IsEven(this int num)
        {
            return num % 2 == 0;
        }
    }

    class Program
    {
        static void Main(string[] args)
        { 
            int num = 10;
            //直接调用扩展方法
            Console.WriteLine("Is {0} a even number? {1}", num, num.IsEven());
            num = 11;
            //直接调用扩展方法
            Console.WriteLine("Is {0} a even number? {1}", num, num.IsEven());
            //经过静态类调用静态方法
            Console.WriteLine("Is {0} a even number? {1}", num, ExtentionMethods.IsEven(num));

            Console.Read();         
        }
    }
}
复制代码

虽然这个例子很是简单,但却演示了扩展方法的使用。测试

调用扩展方法

经过上面的例子能够看到,当调用扩展方法的时候,能够像调用实例方法同样。这就是咱们使用扩展方法的缘由之一,咱们能够给一个已有类型"添加"一个方法。ui

既然扩展方法是一个静态类的方法,咱们固然也能够经过静态类来调用这个方法。this

经过IL能够看到,其实扩展方法也是编译器为咱们作了一些转换,将扩展方法转化成静态类的静态方法调用url

复制代码
IL_001f: nop
IL_0020: ldc.i4.s 11
IL_0022: stloc.0
IL_0023: ldstr "Is {0} a even number? {1}"
IL_0028: ldloc.0
IL_0029: box [mscorlib]System.Int32
IL_002e: ldloc.0
//直接调用扩展方法
IL_002f: call bool ExtentionMethodTest.ExtentionMethods::IsEven(int32)
IL_0034: box [mscorlib]System.Boolean
IL_0039: call void [mscorlib]System.Console::WriteLine(string, object, object)
IL_003e: nop
IL_003f: ldstr "Is {0} a even number? {1}"
IL_0044: ldloc.0
IL_0045: box [mscorlib]System.Int32
IL_004a: ldloc.0
//经过静态类调用静态方法
IL_004b: call bool ExtentionMethodTest.ExtentionMethods::IsEven(int32)
IL_0050: box [mscorlib]System.Boolean
IL_0055: call void [mscorlib]System.Console::WriteLine(string, object, object)
IL_005a: nop
IL_005b: call int32 [mscorlib]System.Console::Read()
IL_0060: pop
IL_0061: ret
复制代码

有了扩展方法,当调用扩展方法的时候,咱们就像是调用一个实例方法。可是,咱们应该从两个角度看这个问题:

  • 经过扩展方法,可使一些方法的调用变得更加通俗易懂,与实例的关系看起来更协调。就例如,"num.IsEven()"这种写法。
    • 基于这个缘由,能够考虑把代码中静态工具类中的一些方法变成扩展方法
  • 固然正是因为扩展方法的调用跟实例方法同样,因此想要一眼就看出一个方法是否是扩展方法不那么容易
    • 其实在VS中仍是很好辨别的,对于上面的例子,在VS中放上鼠标,就能够看到"(extention) bool int.IsEven()"

扩展方法是怎样被发现的

知道怎样调用扩展方法是咱们前面部分介绍的,可是知道怎样不调用扩展方法一样重要。下面就看看编译器怎样决定要使用的扩展方法。

编译器处理扩展方法的过程:当编译器看到一个表达式好像是调用一个实例方法的时候,编译器就会查找全部的实例方法,若是没有找到一个兼容的实例方法,编译器就会去查找一个合适的扩展方法;编译器会检查导入的全部命名空间和当前命名空间中的全部扩展方法,并匹配变量类型到扩展类型存在一个隐式转换的扩展方法。

当编译器查找扩展方法的时候,它会检查System.Runtime.CompilerServices.ExtensionAttribute属性来判断一个方法是不是扩展方法

看到了编译器怎么处理扩展方法了,那么就须要了解一下使用扩展方法时要注意的地方了。

扩展方法使用的注意点:

  • 实例方法的优先级高于扩展方法,当有扩展方法跟实例方法签名一致的时候,编译器不会给出任何警告,而是默认调用实例方法
  • 若是存在多个适用的扩展方法,它们能够应用于不一样的扩展类型(使用隐式转换),那么经过在重载的方法中应用的"更好的转换"规则,编译器会选择最合适的一个
  • 在扩展方法的调用中,还有一个规则,编译器会调用最近的namespace下的扩展方法
  • 扩展方法的类最好和调用扩展方法的类在同一个命名空间下。若是不在同一命名空间下,须要使用using将扩展方法的类的命名空间在当前调用的类里引用一下,(如:using TestWeb.Common;)

下面看一个例子,经过这个例子来更好的理解编译器处理扩展方法时的一些注意点:

复制代码
namespace ExtentionMethodTest
{
    using AnotherNameSpace;
    public static class ExtentionMethods
    {
        public static void printInfo(this Student stu)
        {
            Console.WriteLine("printInfo(Student) from ExtentionMethodTest");
            Console.WriteLine("{0} is {1} years old", stu.Name, stu.Age);
        }

        public static void printInfo(this object stu)
        {
            Console.WriteLine("printInfo(object) from ExtentionMethodTest");
            Console.WriteLine("{0} is {1} years old", ((Student)stu).Name, ((Student)stu).Age);
        }
    }

    public class Student
    {
        public string Name { get; set; }
        public int Age { get; set; }

        //实例方法
        //public void printInfo()
        //{
        //    Console.WriteLine("{0} is {1} years old", this.Name, this.Age);
        //}
    }

    class Program
    {
        static void Main(string[] args)
        {
            Student wilber = new Student { Name = "Wilber", Age = 28 };
            //当实例方法printInfo存在的时候,全部的扩展方法都不可见
            //此时调用的是实例方法
            //wilber.printInfo();

            //当注释掉实例方法后,下面代码会调用最近的命名空间的printInfo方法
            //同时下面语句会选择“更好的转换”规则的扩展方法
            //printInfo(Student) from ExtentionMethodTest
            //Wilber is 28 years old
            wilber.printInfo();

            //当把wilber转换成object类型后,会调用printInfo(this object stu)
            //printInfo(object) from ExtentionMethodTest
            //Wilber is 28 years old
            object will = wilber;
            will.printInfo();

            Console.Read();
        }
    }
}

namespace AnotherNameSpace
{
    using ExtentionMethodTest;
    public static class ExtentionClass
    {
        public static void printInfo(this Student stu)
        {
            Console.WriteLine("printInfo(Student) from AnotherNameSpace");
            Console.WriteLine("{0} is {1} years old", stu.Name, stu.Age);
        }
    }
}
复制代码

空引用上调用扩展方法

当咱们在空引用上调用实例方法是会引起NullReferenceException异常的。

可是,咱们能够在空引用上调用扩展方法。

看下面的例子,咱们能够判断一个对象是否是空引用。

复制代码
namespace ExtentionMethodTest
{
    public static class NullUitl
    {
        public static bool IsNull(this object o)
        {
            return o == null;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            object x = null;
            Console.WriteLine(x.IsNull());
            x = new object();
            Console.WriteLine(x.IsNull());

            Console.Read();
        }
    }
}
复制代码

经过上面的例子能够看到,即便引用为空,"x.IsNull()"仍然可以正常执行。

根据咱们前面介绍的扩展方法的工做原理,其实上面的调用会被编译器转换为静态方法的调用"NullUitl.IsNull(x)"(能够查看IL代码验证),这也就解释了为何空引用上能够调用扩展方法。

总结

本文介绍了扩展方法的使用以及工做原理,其实扩展方法的本质就是经过静态类调用静态方法,只不过是编译器帮咱们完成了这个转换。

而后还介绍了编译器是如何发现扩展方法的,以及使用扩展方法时要注意的地方。了解了编译器怎么查找扩展方法,对编写和调试扩展方法都是有帮助的。

 

出处:http://www.cnblogs.com/wilber2013/p/4307282.html

==============================================================================================

      前言:上篇 序列化效率比拼——谁是最后的赢家Newtonsoft.Json 介绍了下序列化方面的知识。看过Demo的朋友可能注意到了里面就用到过泛型的扩展方法,本篇打算总结下C#扩展方法的用法。博主打算分三个层面来介绍这个知识点,分别是:.Net内置对象的扩展方法、通常对象的扩展方法、泛型对象的扩展方法。

     什么是扩展方法?回答这个问题以前,先看看咱们通常状况下方法的调用。相似这样的通用方法你必定写过:

复制代码
        static void Main(string[] args)
        {

            string strRes = "2013-09-08 14:12:10";
            var dRes = GetDateTime(strRes);
        }

    
        //将字符串转换为日期
        public static DateTime GetDateTime(string strDate)
        {
            return Convert.ToDateTime(strDate);
        }

        //获得非空的字符串
        public static string GetNotNullStr(string strRes)
        {
            if (strRes == null)
                return string.Empty;
            else
                return strRes;
        }
复制代码

或者在项目中有一个相似Utils的工具类,里面有多个Helper,例如StringHelper、XmlHelper等等,每一个Helper里面有多个static的通用方法,而后调用的时候就是StringHelper.GetNotNullStr("aa");这样。还有一种普通的用法就是new 一个对象,经过对象去调用类里面的非static方法。反正博主刚开始作项目的时候就是这样写的。后来随着工做经验的累积,博主看到了扩展方法的写法,立马就感受本身原来的写法太Low了。进入正题。

 

一、.Net内置对象的扩展方法

.Net内部也有不少定义的扩展方法,例如咱们Linq经常使用的Where(x=>x==true)、Select()等等。当你转到定义的时候你很容易看出来:public static IEnumerable<TSource> Where<TSource>(this IEnumerable<TSource> source, Func<TSource, bool> predicate)。固然咱们也能够给.Net对象新增扩展方法,好比咱们要给string对象加一个扩展方法(注意这个方法不能和调用的Main方法放在同一个类中):

复制代码
        public static string GetNotNullStr(this string strRes)
        {
            if (strRes == null)
                return string.Empty;
            else
                return strRes ;
        }
复制代码

而后在Main方法里面调用:

        static void Main(string[] args)
        {
            string strTest = null;
            var strRes = strTest.GetNotNullStr();
        }

简单介绍:public static string GetNotNullStr(this string strRes)其中this string就表示给string对象添加扩展方法。那么在同一个命名空间下面定义的全部的string类型的变量均可以.GetNotNullStr()这样直接调用。strTest.GetNotNullStr();为何这样调用不用传参数,是由于strTest就是做为参数传入到方法里面的。你能够试试。使用起来就和.Net framework定义的方法同样:

 

     固然除了string,你能够给.Net内置的其余对象加扩展方法,例如给DataGridViewRow的扩展方法:

//DataGridViewRow的扩展方法,将当前选中行转换为对应的对象
        public static T ToObject<T>(this DataGridViewRow item) where T:class
        {
            var model = item.DataBoundItem as T;
            if (model != null)
                return model;
            var dr = item.DataBoundItem as System.Data.DataRowView;
            model = (T)typeof(T).GetConstructor(new System.Type[] { }).Invoke(new object[] { });//反射获得泛型类的实体
            PropertyInfo[] pro = typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public);
            Type type = model.GetType();
            foreach (PropertyInfo propertyInfo in pro)
            {
                if (Convert.IsDBNull(dr[propertyInfo.Name]))
                {
                    continue;
                }
                if (!string.IsNullOrEmpty(Convert.ToString(dr[propertyInfo.Name])))
                {
                    var propertytype = propertyInfo.PropertyType;
                }
            }
            return model;
        }
View Code

这样看上去就像在扩展.Net Framework。有没有感受有点高大上~

 

二、通常对象的扩展方法

     和Framework内置对象同样,自定义的对象也能够增长扩展方法。直接上示例代码:

    public class Person
    {
        public string Name { set; get; }
        public int Age { set; get; }
    }
复制代码
        //Person的扩展方法,根据年龄判断是不是成年人
        public static bool GetBIsChild(this Person oPerson)
        {
            if (oPerson.Age >= 18)
                return false;
            else
                return true;
        }
复制代码

Main方法里面调用:

var oPerson1 = new Person();
oPerson1.Age = 20;
var bIsChild = oPerson1.GetBIsChild();        

和string扩展方法相似,就很少作解释了。

 

三、泛型对象的扩展方法

      除了上面两种以外,博主发现其实能够定义一个泛型的扩展方法。那么,是否是全部的类型均可以直接使用这个扩展方法了呢?为了保持程序的严谨,下面的方法可能没有实际意义,当开发中博主以为可能存在这种场景:

复制代码
public static class DataContractExtensions
{
  //测试方法
  public static T Test<T>(this T instance) where T : Test2
  {
       T Res = default(T);
       try
       {
           Res.AttrTest = instance.AttrTest.Substring(0,2);
           //其余复杂逻辑...


      }
      catch
      { }
      return Res;
  }

}

public class Test2
{
  public string AttrTest { set; get; }
}
复制代码

 

使用扩展方法有几个值得注意的地方:

(1)扩展方法不能和调用的方法放到同一个类中

(2)第一个参数必需要,而且必须是this,这是扩展方法的标识。若是方法里面还要传入其余参数,能够在后面追加参数

(3)扩展方法所在的类必须是静态类

(4)扩展方法的类最好和调用扩展方法的类在同一个命名空间下。若是不在同一命名空间下,须要使用using将扩展方法的类的命名空间在当前调用的类里引用一下,(如:using TestWeb.Common;)

 

可能你第一次使用这个会以为很别扭。你也许会说扩展方法和我之前用的static方法不管从代码实现仍是算法效率都差很少嘛,是的!确实差很少,但使用多了以后会发现它确实能帮你省去不少代码。

 

出处:http://www.cnblogs.com/landeanfen/p/4632467.html

===========================================================================================

另外参考微软的说明文档:

扩展方法(C# 编程指南)

如何:实现和调用自定义扩展方法(C# 编程指南)

如何:为枚举建立新方法(C# 编程指南)

相关文章
相关标签/搜索