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)
Eri*_*ert 48
C#规范规定所有委托类型必须可转换为System.Delegate.实际上,实现实现它的方式是所有委托类型都是从派生而来的System.MulticastDelegate,而派生自System.Delegate.
明白了吗?我不确定是否回答了你的问题.
Mik*_*keM 11
"所有委托实例都具有多播功能." - http://msdn.microsoft.com/en-us/library/orm-9780596527570-03-04.aspx
"在C#中,所有代理类型都支持多播" - http://msdn.microsoft.com/en-us/library/orm-9780596516109-03-09.aspx
澄清一点:所有委托都是类的实例MulticastDelegate,无论它们是否有一个或多个目标方法.原则上,具有单个或多个目标的委托之间没有区别,尽管运行时针对具有单个目标的常见情况稍微优化.(虽然不可能有0个目标的代表,但它是一个或多个.)
在实例化类似委托时new MyMethodHandler(Method1),可以使用单个目标(Method1方法)创建委托.
通过组合两个现有委托来创建具有多个目标的代理.结果代表将拥有目标总和.代理可以显式组合Delegate.Combine(),也可以通过+=在现有委托上使用运算符隐式组合,如示例中所示.
调用委托依次调用委托中的每个目标.因此,在您的示例中,handler(someObject);将调用两个方法(Method1和Method2),因为您已经使用这两个目标创建了一个委托.
| 归档时间: |
|
| 查看次数: |
53967 次 |
| 最近记录: |