本文介绍了在 C# 中是否有一个不是 MulticastDelegate 的委托?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我认为答案是否定的?如果没有,为什么我们要分开 DelegateMulticastDelegate 类?也许又是因为其他一些 .NET 语言"?

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"?

推荐答案

认为这是 ECMA 335 的一部分,但我在任何地方都看不到它.

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

你不能在 C# 中创建这样的委托类型,但你可以在 IL 中:

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
}

C# 编译器使用这样的委托没有问题:

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

但是 CLR 在尝试加载它时会这样做:

But the CLR does when it tries to load it:

未处理的异常:System.TypeLoadException:无法从程序集Foo,Version=0.0.0.0,Culture=neutral,PublicKeyToken=null"加载类型Foo",因为它不能直接从委托类继承.在 Test.Main()

基本上,Delegate/MulticastDelegate 分离是一个历史性的意外.我相信早期的 alpha/beta 版本确实做出了区分,但事实证明它太混乱而且通常没有用 - 所以现在 每个 委托都派生自 MulticastDelegate.

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.

(有趣的是,C# 规范在不能用作泛型约束的类型列表中只提到了一次 MulticastDelegate.)

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

这篇关于在 C# 中是否有一个不是 MulticastDelegate 的委托?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-15 06:07