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

it2022-05-05  82

C#3.0 为我们带来什么(6) —— 扩展方法 在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是有本质不同的。 posted on 2008-01-06 19:40 tianyamoon 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/tianyamoon/archive/2008/01/06/1028039.html

相关资源:各显卡算力对照表!

最新回复(0)