给已有类添加附件方法

来源:互联网 发布:中央网络电视台官网 编辑:程序博客网 时间:2024/04/28 21:31

在某些时候,需要给已有的类添加 本身没有的方法,比如说 给 数组(Array) 添加个方法,扩展其大小的,又比如,给string类添加一个方法,可以使其转化成整型的

下面的代码就演示了如何添加一个附加方法

注意,附加方法只能添加在 非泛型的静态类中


在一个非泛型的静态类中添加 静态的方法

public static class Class1    {        public static int ToInt(this string str)   //如果要传入参数则在后面添加参数 如(this string str, string a)        {            try            {                return Convert.ToInt32(str);                  }            catch (Exception ex)            {                return 0;            }        }    }


然后调用

  static void Main(string[] args)        {            string a = "123";            int b = a.ToInt();            Console.WriteLine(b+3);            Console.Read();        }

得到结果为 

126;

0 0
原创粉丝点击