C# 之扩展方法

在编程过程中,有时由于新的需求,可能就会需要对类型进行修改,但当需要为类型添加新功能但并不拥有类型的已有代码时,就需要用到 扩展方法;

使用扩展方法的方式:创建一个新的类,这个类必须是静态类.

          在这个类中添加需要增加的方法,方法的第一个参数是要扩展的类型,且必须用this修饰.

 class Program
    {
       
        static void Main(string[] args)
        {
            Test test = new Test();

            test.write(2);//通过实例调用
            LX.write(test,2);//直接静态调用
            Console.ReadKey();

        }

    }

    public static class LX {
        public static void write(this object obj,int i)//obj表示要扩展的类型,必须用this修饰
        {
            Console.WriteLine("扩展方法");
        }
    }

输出结果       

原文地址:https://www.cnblogs.com/lzyqq/p/11389228.html