问题描述
我已经深入阅读了一些有关委托的内容,令人困惑的是,使用一种方法的委托可能与多播委托不同.但是,通过反射,您可以清楚地看到,即使仅使用一种方法,委托确实是从 MulticastDelegate
派生的,而不是立即从 Delegate
对象.
I have been reading a bit about delegates in depth, it is confusing that a delegate with one method could be different than a multicast delegate. However, via reflection, you can see plainly that even with only a single method, a delegate is indeed deriving from MulticastDelegate
, and not immediately deriving from a Delegate
object.
class Program
{
public delegate void MyDelegate();
static void SomeMethod()
{
}
static void Main(string[] args)
{
MyDelegate del = null;
del = new MyDelegate(SomeMethod);
Console.WriteLine(del.GetType().BaseType.Name);
Console.ReadKey();
}
}
输出: MulticastDelegate
我意识到 MulticastDelegate
包含 Delegate
对象的调用列表.我想知道是否有可能直接创建单个 Delegate
,并且这样做是否有好处,除了调用 GetInvocationList()
并提取单独委托
对象.
I realize that a MulticastDelegate
contains an invocation list of Delegate
objects. I am wondering if it is possible to create a single Delegate
directly and if there would be any advantage to doing so, other than calling GetInvocationList()
and extracting the Delegate
objects individually.
推荐答案
不是.所有.NET委托均来自 MulticastDelegate
.最初编写.NET时,单"和."之间是有区别的.多播,但该区别在发布之前已被删除.但是,基础类型没有合并为一个.
Not really. All .NET delegates are derived from MulticastDelegate
. When .NET was first written, there was originally a difference between single & multicast, but that distinction was dropped before release. However, the underlying types weren't merged into one.
您不能直接在C#中从 Delegate
派生.您也许可以使用原始IL,但是没有什么真正的意义,因为 MulticastDelegate
的运行方式像单播委托,可以实现所有意图和目的.
You can't derive from Delegate
directly in C#. You might be able to in raw IL, but there's not really much point, as a MulticastDelegate
operates like a singlecast delegate to all intents and purposes.
这篇关于.NET单一代理与多播代理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!