zoukankan      html  css  js  c++  java
  • C#扩展方法实现

         C#提供了一种机制,可以扩展系统或者第三方类库中的方法。比如说想在string类型的对象里面多一个ToInt32(),来方便的将字符转换成整形。在实现的过程中的关键字为static和this即可。
         下面我们来做一个在string类型中新建一个ToInt32的自定义方法:

    public static class Extension//必须先声明一个静态类,类名随意
        {
            public static int ToInt32(this string In)//扩建的方法必须是静态方法,参数里面必须含有this关键字,this关键字后面的类型为需要扩展的类型
            {
                return Convert.ToInt32(In);
            }
        }

          那么在使用string的对象的时候,会多出一个ToInt32的方法。

    static void Main(string[] args)
    {
           string a = "1";
           int b = a.ToInt32();
           Console.ReadLine();
    }

          既然可以扩展.net的内置类型,扩展自定义类型也是可以的。

    public class A//先定义A类
        {
        }

        public static class Extension//必须先声明一个静态类,类名随意
        {
            public static int ToInt32(this string In)//扩建的方法必须是静态方法,参数里面必须含有this关键字,this关键字后面的类型
            {
                return Convert.ToInt32(In);
            }
            //为A新增一个ExtensionMethod方法
            public static string ExtensionMethod(this A a)//扩建的方法必须是静态方法,参数里面必须含有this关键字,this关键字后面的类型
            {
                return "this is extension method";
            }
        }

         在使用A的对象的时候,会多出一个ExtensionMethod方法:

    static void Main(string[] args)
    {
          string a = "1";
          int b = a.ToInt32();
          A c = new A();
          string d = c.ExtensionMethod();
          Console.ReadLine();
    }

  • 相关阅读:
    jstl动态生成下拉列表框
    nested exception is java.lang.NoClassDefFoundError:org/hibernate/engine/SessionFactoryImplementor
    java.lang.NoSuchMethodError: ognl.SimpleNode.isEvalChain(Lognl/OgnlContext;)Z
    java.lang.NoClassDefFoundError: org/apache/commons/lang3/StringUtils
    java.lang.NoSuchMethodError: javax.persistence.OneToOne.orphanRemoval()Z
    substring(int beginIndex,int length)的参数
    reverse() 颠倒StringBuffer对象中的字符
    jsp servlet 分页
    & | && ||
    C++ 导入导出
  • 原文地址:https://www.cnblogs.com/vveiliang/p/6440928.html
Copyright © 2011-2022 走看看