简单委托(委托)与多播委托

Simple Delegate (delegate) vs. Multicast delegates(简单委托(委托)与多播委托)

本文介绍了简单委托(委托)与多播委托的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我浏览了很多文章,但我仍然不清楚我们通常创建的普通委托和多播委托之间的区别.

I have gone through many articles but I am still not clear about the difference between the normal delegates that we usually create and multicast delegates.

public delegate void MyMethodHandler(object sender);
MyMethodHandler handler = new MyMethodHandler(Method1);
handler += Method2;
handler(someObject);

上面的委托 MyMethodHandler 会调用这两个方法.现在多播委托从何而来.我读过他们可以调用多种方法,但我担心我对委托的基本理解是不正确的.

The above delegate MyMethodHandler will call these two methods. Now where does multicast delegates come in. I have read that they can call multiple methods but I am afraid that my basic understanding about delegates is not correct.

推荐答案

这篇文章 解释得很好:

delegate void Del(string s);

class TestClass
{
    static void Hello(string s)
    {
        System.Console.WriteLine("  Hello, {0}!", s);
    }

    static void Goodbye(string s)
    {
        System.Console.WriteLine("  Goodbye, {0}!", s);
    }

    static void Main()
    {
        Del a, b, c, d;

        // Create the delegate object a that references 
        // the method Hello:
        a = Hello;

        // Create the delegate object b that references 
        // the method Goodbye:
        b = Goodbye;

        // The two delegates, a and b, are composed to form c: 
        c = a + b;

        // Remove a from the composed delegate, leaving d, 
        // which calls only the method Goodbye:
        d = c - a;

        System.Console.WriteLine("Invoking delegate a:");
        a("A");
        System.Console.WriteLine("Invoking delegate b:");
        b("B");
        System.Console.WriteLine("Invoking delegate c:");
        c("C");
        System.Console.WriteLine("Invoking delegate d:");
        d("D");
    }
}
/* Output:
Invoking delegate a:
  Hello, A!
Invoking delegate b:
  Goodbye, B!
Invoking delegate c:
  Hello, C!
  Goodbye, C!
Invoking delegate d:
  Goodbye, D!
*/

这篇关于简单委托(委托)与多播委托的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:简单委托(委托)与多播委托

基础教程推荐