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

A9S*_*9S6 64 .net c# delegates multicastdelegate

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

public delegate void MyMethodHandler(object sender);
MyMethodHandler handler = new MyMethodHandler(Method1);
handler += Method2;
handler(someObject);
Run Code Online (Sandbox Code Playgroud)

上面的委托MyMethodHandler将调用这两个方法.现在多播代表的位置在哪里.我已经读过它们可以调用多种方法,但我担心我对代理的基本理解是不正确的.

Dar*_*rov 75

这篇文章很好地解释了它:

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!
*/
Run Code Online (Sandbox Code Playgroud)

  • .NET*中的代表是*多播代理(据我所知).无论您是选择将零个还是一个或多个处理程序附加到它们,它们仍然是多播委托. (51认同)
  • @MikeChristian获得了"多播委托将以不可预测的顺序呼叫其订户"的链接?第二段[15.3](http://msdn.microsoft.com/en-us/library/aa664605%28VS.71%29.aspx)似乎是说这就是所谓的秩序. (12认同)
  • Multicast委托只是在其调用列表中具有多个方法引用的普通委托吗? (11认同)
  • 值得注意的是,多播委托将以不可预测的顺序呼叫其订户.不要以为它们会以任何特定顺序被调用. (8认同)
  • 究竟.多播委托将调用多个方法. (3认同)

Eri*_*ert 48

C#规范规定所有委托类型必须可转换为System.Delegate.实际上,实现实现它的方式是所有委托类型都是从派生而来的System.MulticastDelegate,而派生自System.Delegate.

明白了吗?我不确定是否回答了你的问题.

  • 是埃里克.通常当我向人们(或人们问我)询问代表时,我们通常会说有两种类型的代表 - 单播和多播.现在我知道只有一个像'委托'这样的东西可以是单播或多播,这取决于它包含的方法引用的数量. (25认同)

Jac*_*esB 5

澄清一点:所有委托都是类的实例MulticastDelegate,无论它们是否有一个或多个目标方法.原则上,具有单个或多个目标的委托之间没有区别,尽管运行时针对具有单个目标的常见情况稍微优化.(虽然不可能有0个目标的代表,但它是一个或多个.)

在实例化类似委托时new MyMethodHandler(Method1),可以使用单个目标(Method1方法)创建委托.

通过组合两个现有委托来创建具有多个目标的代理.结果代表将拥有目标总和.代理可以显式组合Delegate.Combine(),也可以通过+=在现有委托上使用运算符隐式组合,如示例中所示.

调用委托依次调用委托中的每个目标.因此,在您的示例中,handler(someObject);将调用两个方法(Method1Method2),因为您已经使用这两个目标创建了一个委托.