c#拓展方法

对于已经定义好的类,对其进行拓展方法

下面我们给出对于String类和Int类的拓展方法的举例:

    static class Demo3
    {
        public static void Test1()
        {
            string str = "夜空中最亮的星";
            str.TestMethod();
        }

        public static void Test2()
        {
            int num = 88;
            num.TestMethod();
        }

        public static int TestMethod(this int name)
        {
            Console.WriteLine("老子是拓展方法");
            return 110;
        }

        static void Main(string[] args)
        {
           Test2();
        }
    }

***我们注意的是拓展的类必须是静态类,而且方法也应该是静态的,

    应该使用一些关键字表明这个方法是类的拓展方法,this int name,拓展的是Int类。

猜你喜欢

转载自www.cnblogs.com/Optimism/p/10491900.html