C# 中的扩展方法

 在定义扩展方法时,有三个限制
  一:必须把方法定义在静态类中,所以每个扩展方法也必须定义为静态的;(这是因为静态类先编译,所以它才能被别的类调用)
  二:所有的扩展方法都需要使用this对第一个参数(并且只对第一个参数)进行修饰;(这里的this修饰的就是该扩展方法所能被调用的类型。)
  三:每个扩展方法只可以被内存中正确的实例调用。(也就是当二中this 修饰的是int类型,那么这个扩展方法也就只能被int的实例所点出来。)
  还是以例子看明白吧。

        

View Code
 1 static class MyExtensions
 2     { 
 3 
 4 
 5     //本方法允许任何对象显示它所处的程序集
 6         public static void DisplayDefiningAssembly(this object obj)
 7         {
 8             Console.WriteLine("{0} lives here : =>> {1} \n",obj.GetType().Name,Assembly.GetAssembly(obj.GetType()).GetName().Name);
 9         }
10 
11 
12         //本方法允许任何整型返回倒置的副本,如56将返回65;
13         public static int ReverseDigits(this int i)
14         { 
15         //把int 翻译为string 然后获取所有字符
16             char[] digits = i.ToString().ToCharArray();
17 
18             //反转数组中的项
19             Array.Reverse(digits);
20 
21             //放回string 
22             string newDigits = new string(digits);
23 
24             //最后以int返回修改后的字符串
25             return int.Parse(newDigits);
26         }
27     }

 在Main()方法中这样调用 下:

View Code
1   static void Main(string[] args)
2         {
3             int i = 0;
4             i.DisplayDefiningAssembly();
5             System.Data.DataSet ds = new System.Data.DataSet();
6             ds.DisplayDefiningAssembly();
7             Console.ReadKey();
8         }

显示结果如下:


 

原文地址:https://www.cnblogs.com/haofaner/p/2467595.html