C# 委托

委托三步

1. 声明 declaration :   delegate <返回值类型> *EventHandler(<参数列表>);        EvnetHandler为委托名后缀规范

2. 实例化 instantiation   *EventHandler a;    或者  *EventHandler a = new *EventHandler(<方法>);

3. 调用 call    a(<参数>);


样例代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

delegate void MyDelegateEventHandler(string s);    // declare a delegate, EventHandler是后缀规范
namespace ConsoleACsharp1
{
   
    class Class1
    {

        void PrintFirst(string str)
        {
            Console.WriteLine("{0} ,My First Delegate", str);
        }


        void PrintSecond(string str)
        {
            Console.WriteLine("{0}, My Second Delegate", str);
        }

        static void Main(string[] args)
        {
            Class1 ob = new Class1();
            // instantiation a object  // 相当于创建了一个指向函数的指针
            //MyDelegateEventHandler c1 = new MyDelegateEventHandler(ob.PrintFirst);

            MyDelegateEventHandler c1;
            c1 = ob.PrintFirst;
            c1 += ob.PrintSecond;  // 添加一个要委托的事件
            // call  
            c1("call!");
        }
    }
}

注意: 委托和 要委托的方法的 参数列表形式和返回值类型要相同


猜你喜欢

转载自blog.csdn.net/chenbetter1996/article/details/80151341