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

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

上面的委托MyMethodHandler将调用这两个方法.

推荐答案

This article很好地解释了这一点:

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!
*/

.net相关问答推荐

Long.MaxValue从Single到Long的转换导致溢出异常

";Make Async ValueTask/ValueTask方法分期分配发生了什么?

如何通过在后台预加载流项来优化流迭代的性能?

为什么解码后的字节数组与原始字节数组不同?

正则表达式匹配 URL 中的多个子目录

将日期时间转换为日期格式 dd/mm/yyyy

比较 C# 中的双精度值

C#6.0 字符串插值本地化

AutoMapper 的替代品

您是否使用 TestInitialize 或测试类构造函数来准备每个测试?为什么?

mstest.exe 在哪里?

获取当前方法的名称

如何使用转储文件来诊断内存泄漏?

C# 中的 myCustomer.GetType() 和 typeof(Customer) 有什么区别?

C# 相当于 Java 的 <?在泛型中扩展 Base>

您可以在 C# 代码中捕获本机异常吗?

错误 NU1605 检测到包降级

如何使用 DateTime 指定一天中的最晚时间

有没有一种简单的方法来判断 .NET Framework 版本?

如何使用 AutoMapper .ForMember?