zoukankan      html  css  js  c++  java
  • 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是有本质不同的。
  • 相关阅读:
    shell脚本查找tcp过多ip地址封掉
    tomcat日志传参乱码问题
    nginx部署vue跨域proxy方式
    nginx部署VUE跨域访问api
    springboot2.1.3 + redisTemplate + Lock 操作 redis 3.0.5
    java8 lamb表达式对List排序
    Mysql5.7降级到5.6遇到的坑
    mac中git使用
    mac中git flow使用
    mac安装openjdk8-maven-mysql-git-docker
  • 原文地址:https://www.cnblogs.com/tianyamoon/p/1028039.html
Copyright © 2011-2022 走看看