MVC09

1.委托(delegate)调用静态方法 

委托类似于C++中的函数指针。

某方法仅仅在执行的时候才能确定是否被调用。

是实现事件和回调函数的基础。

面向对象,安全性高.

using System;
using System.IO;

namespace IO
{
    class Program
    {
        // 声明一个delegate(委托)
        delegate int NumberChanger(int n);
        static int num = 10;
        static void Main(string[] args)
        {
            // 实例化一个委托,构造函数内是符合要求的静态函数
            NumberChanger nc1 = new NumberChanger(AddNum);
            // 调用方式与调用方法一致
            nc1(120);
            Console.WriteLine(num);
        }

        // 声明一个符合要求的静态方法,该方法的返回值以及参数列表必须与所声明的委托一致

        public static int AddNum(int p)
        {
            num += p;
            return num;
        }
    }

}

2.通过委托调用实例化方法

using System;
using System.IO;

namespace IO
{
    class Program
    {
        // 声明一个delegate(委托)
        delegate int NumberChanger(int n);
        static void Main(string[] args)
        {
            MyClass mc = new MyClass();
            NumberChanger nc2 = new NumberChanger(mc.AddNum);
            Console.WriteLine(nc2(1));
        }

    }

    class MyClass
    {
        private int num = 60;
        public int AddNum(int p)
        {
            num += p;
            return num;
        }
    }

}

3. multi-delegete(多重委托)

同时委托调用多个方法

using System;
using System.IO;

namespace IO
{
    class Program
    {
        delegate void D(int x);
        static void Main(string[] args)
        {

            D cd1 = new D(C.M1);
            cd1(-1);
            Console.WriteLine();
            D cd2 = new D(C.M2);
            cd1(-2);
            Console.WriteLine();
            D cd3 = cd1 + cd2;
            cd3(10);
            Console.WriteLine();

            C c = new C();
            D cd4 = new D(c.M3);
            cd3 += cd4;
            cd3(100);
            Console.WriteLine();

            cd3 -= cd4;
            cd3(1000);
        }

    }

    class C
    {
        public static void M1(int i)
        {
            Console.WriteLine("C.M1" + i);
        }

        public static void M2(int i)
        {
            Console.WriteLine("C.M2" + i);
        }

        public void M3(int i)
        {
            Console.WriteLine("C.M3" + i);
        }
    }

    
}
原文地址:https://www.cnblogs.com/Tanqurey/p/12260244.html