我找不到在反射器+运算下Delegate
或MulticastDelegate
.
我试图找出这不需要演员如何:
Action a = () => Console.WriteLine("A");
Action b = () => Console.WriteLine("B");
Action c = a + b;
Run Code Online (Sandbox Code Playgroud)
但这样做:
Action a = () => Console.WriteLine("A");
Action b = () => Console.WriteLine("B");
Action c = (Action)MulticastDelegate.Combine(a, b);
Run Code Online (Sandbox Code Playgroud)
在第一个样本中,是否在封面下完成了演员表?
+=
并且-=
在语言级别(即使用编译器帮助)实现了已知的委托类型,因此它不需要强制转换,而Delegate.Combine
只是一个具有Delegate
返回类型的普通(非泛型)方法,因此需要强制转换.
以下面的例子为例:
class Program
{
static void Main(string[] args)
{
Test1();
Test2();
}
public static void Test1()
{
Action a = () => Console.WriteLine("A");
Action b = () => Console.WriteLine("B");
Action c = a + b;
c();
}
public static void Test2()
{
Action a = () => Console.WriteLine("A");
Action b = () => Console.WriteLine("B");
Action c = (Action)MulticastDelegate.Combine(a, b);
c();
}
}
Run Code Online (Sandbox Code Playgroud)
然后用ILSpy查看:
internal class Program
{
private static void Main(string[] args)
{
Program.Test1();
Program.Test2();
}
public static void Test1()
{
Action a = delegate
{
Console.WriteLine("A");
};
Action b = delegate
{
Console.WriteLine("B");
};
Action c = (Action)Delegate.Combine(a, b);
c();
}
public static void Test2()
{
Action a = delegate
{
Console.WriteLine("A");
};
Action b = delegate
{
Console.WriteLine("B");
};
Action c = (Action)Delegate.Combine(a, b);
c();
}
}
Run Code Online (Sandbox Code Playgroud)
看起来他们做的事情完全相同,只是 C# 在第一个测试中提供了一些语法糖。