Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
453 views
in Technique[技术] by (71.8m points)

.net - Is there a Delegate which isn't a MulticastDelegate in C#?

I think the answer is NO? If there isn't, why do we have separated Delegate and MulticastDelegate classes? Maybe it's again because of "some other .NET languages"?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

EDIT: I thought this was part of ECMA 335, but I can't see it in there anywhere.

You can't create such a delegate type in C#, but you can in IL:

.class public auto ansi sealed Foo
       extends [mscorlib]System.Delegate
{
    // Body as normal
}

The C# compiler has no problems using such a delegate:

using System;

class Test
{
    static void Main()
    {
        Foo f = x => Console.WriteLine(x);
        f("hello");
    }
}

But the CLR does when it tries to load it:

Unhandled Exception: System.TypeLoadException: Could not load type 'Foo' from assembly 'Foo, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' because it cannot inherit directly from the delegate class. at Test.Main()

Basically the Delegate/MulticastDelegate separation is an historical accident. I believe that early alpha/beta versions did make the distinction, but it proved too confusing and generally not useful - so now every delegate derives from MulticastDelegate.

(Interestingly, the C# specification only mentions MulticastDelegate once, in the list of types which can't be used as generic constraints.)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...