C#3.0 为我们带来什么(6) —— 扩展方法

文/tianyamoon  出处/博客园

在c#3.0中可以出现这样的语法
int i = 2;
Console.WriteLine(i.Square());
这就是扩展方法。

如何使int具有Square方法呢?
只需要定义这样一个函数
        public static int Square(this int i)
      {
            return i * i;
        }
        this 表示针对int的实例和索引器的this的含义是一样的,int表示给int这种类型进行扩展

但是这个扩展函数是有一定限制的。
1 扩展方法必须是静态的
2 扩展方法必须在顶级静态类上定义
来看看IL实现
.method public hidebysig static int32  Square(int32 i) cil managed
{
  .custom instance void [System.Core]System.Runtime.CompilerServices.ExtensionAttribute::.ctor() = ( 01 00 00 00 )
  // 代码大小      9 (0x9)
  .maxstack  2
  .locals init ([0] int32 CS$1$0000)
  IL_0000:  nop
  IL_0001:  ldarg.0
  IL_0002:  ldarg.0
  IL_0003:  mul
  IL_0004:  stloc.0
  IL_0005:  br.s      IL_0007
  IL_0007:  ldloc.0
  IL_0008:  ret
} // end of method MyExtention::Square
C#编译器生成了MyExtention.Square(int32 i),并没有对int类型进行改变。我们可以把他当作visitor模式来使用,但是跟visitor是有本质不同的。

 感谢原创者的辛勤劳动,希望对您有所帮助,转载请注明原出处。
 您可能对 [C#] 的这些文章也感兴趣:

用C#Builder实现文件下载程序
C#中一些字符串操作的常用用法
C#积木模块ABC(二)
Master Pages: Tips, Tricks, and Traps
微软公布“.NET”第二阶段研发方向
.NET框架中的XML:在.NET框架中使用XML架构执行代码生成(3)
C#泛型集合揽胜
在VisualC#中访问不同数据库(4)
解读C#中的正则表达式
用C#编写网络电话