• 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是有本质不同的。
  • 相关阅读:
    Linux下配置Tomcat服务器
    Octopress + GitHub Page 搭建个人博客
    Cocoapods报错Unable to satisfy the following requirements
    类方法load和initialize的区别
    AFNetworking3.0 Post JSON数据
    iOS防止button重复点击
    iOS与H5交互遇到的坑
    cocoapods安装
    平时做的一些好玩或者测试的 项目 特效,动画
    webpack那些事儿
  • 原文地址:https://www.cnblogs.com/tianyamoon/p/1028039.html
Copyright © 2020-2023  润新知