扩展方法(C#)

C#扩展方法在不需要直接更新目标类型的情况下,获得功能上的扩展。

扩展方法必须定义在静态类中,并要使用this关键字对第一个参数(即目标类型)进行修饰。

    static class MyExtensions {

        public static void DisplayDefiningAssembly(this object obj) {

            Console.WriteLine("{0} lives here: {1}", obj.GetType().Name,

                System.Reflection.Assembly.GetAssembly(obj.GetType()));

        }

        public static void Foo(this int i, string msg) {

            Console.WriteLine("{0} called Foo() and msg = {1}", i, msg);

        }

    }

    static void Main(string[] args) {

        int x = 12345;

        //在实例层次上调用扩展方法

        x.DisplayDefiningAssembly();

       

        //C#编译器仅以普通的方式调用静态方法,我们也可以自己静态调用扩展方法

        MyExtensions.DisplayDefiningAssembly(x);

    }

猜你喜欢

转载自blog.csdn.net/Nicky_1218/article/details/85161982