委托和回调函数例子

时间:2021-11-05 17:36:38

其实,回调函数就是把方法当做一个参数传入其它方法中,就算直接传递方法名,那宿主方法该用什么来接收这个方法名呢?(比较绕,其实我们知道,如果参数传入"zhangsan",在宿主方法中可以用string来接收它。传入3,可以用int来接收它)。聪明的您一定想到了,传入方法,就用委托来接收它

啥都不说了,例子是最好的老师!

public delegate void OutPutMsgHandler(string name);


/// <summary>
/// 入口类
/// </summary>
class DelegateClass
{
    static void Main(string[] args)
    {
        Console.WriteLine("程序运行开始……");
        //利用多播委托
        OutPutMsgHandler callbackClass = new OutPutMsgHandler (MethodClass.EnglishGreeting);
        callbackClass += MethodClass.ChineseGreeting;
        new CallBackMethod().DoOutputMessge("zhangsan", callbackClass);
        Console.WriteLine("程序运行结束……");

        Console.ReadLine();
    }
}

public class CallBackMethod
{
    /// <summary>
    /// 回调函数,把方法作为参数传入。
    /// </summary>
    /// <param name=" name "></param>
    /// <param name="callbackMethod"></param>
    public void DoOutputMessge(string name, OutPutMsgHandler callbackMethod)
    {
        callbackMethod(name);
    }
}


/// <summary>
/// 方法类,全部为静态方法,测试调用
/// </summary>
public class MethodClass
{
    public static void EnglishGreeting(string name)
    {
        Console.WriteLine(name + "Morning");
    }

    public static void ChineseGreeting(string name)
    {
        Console.WriteLine(name + "早上好");
    }
}