.NET single vs. multicast delegates [duplicate]

偶尔善良 提交于 2021-01-28 12:51:54

问题


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();
    }
}

Output:MulticastDelegate

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.


回答1:


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.

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.



来源:https://stackoverflow.com/questions/16220151/net-single-vs-multicast-delegates

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!