gpt4 book ai didi

c# - Simple Delegate(委托(delegate))与多播委托(delegate)

转载 作者:IT王子 更新时间:2023-10-29 03:44:43 28 4
gpt4 key购买 nike

我看了很多文章,但我仍然不清楚我们通常创建的普通委托(delegate)和多播委托(delegate)之间的区别。

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

上面的委托(delegate) MyMethodHandler 将调用这两个方法。现在多播委托(delegate)从哪里来。我读过他们可以调用多个方法,但恐怕我对委托(delegate)的基本理解是不正确的。

最佳答案

.NET 中的委托(delegate)是多播委托(delegate)。无论您选择将零个还是一个或多个处理程序附加到它们,它们仍然是多播委托(delegate)。

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

关于c# - Simple Delegate(委托(delegate))与多播委托(delegate),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2192219/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com