无法分配到较少的特定参数类型的委托匿名方法较少、分配、参数、类型

2023-09-03 00:47:30 作者:匿名的关系

我能够分配方法 M 委托对象 D 一个没有特定的参数类型,但当我想用同样的分配匿名方法的签名方法 M D ,我得到一个错误。

这是为什么?

 类derivedEventArgs:EventArgs的{}

委托无效newDelegate(对象o,derivedEventArgs E);

静态无效的主要(字串[] args)
{
    newDelegate D =米; // 好
                D =(对象o,EventArgs五)=> {}; // 错误
}

公共静态无效的M(对象o,EventArgs五){}
 

解决方案

贾里德当然是正确的,这是由设计。

原因:设计是,在逆变方式转换的情况下,你可能有你没有写一个方法,并把它分配给了你没有写任何一个委托变量。你不控制的类型。所以我们去了一下简单的你,让参数匹配contravariantly和返回类型匹配协变。

在λ-到委托的转换,您的不的控制被分配的东西。没有任何的从使它完全匹配的参数类型停止的你,因此,我们的需要的你。这里没有捏造允许的。

.NET 中的多线程 一 概念

I’m able to assign a method M to delegate object d with a less specific parameter type, but when I want to assign an anonymous method with same the signature as method M to d, I get an error.

Why is that?

class derivedEventArgs : EventArgs { }

delegate void newDelegate(object o, derivedEventArgs e); 

static void Main(string[] args)
{
    newDelegate d = M; // ok
                d = (object o, EventArgs e) => { }; // error
}

public static void M(object o, EventArgs e) { }

解决方案

Jared is of course correct that this is by design.

The reason for that design is that in the contravariant method conversion case, you might have a method that you didn't write, and be assigning it to a delegate variable that you didn't write either. You don't control the types. So we go a bit easy on you and let the parameters match contravariantly and the return types match covariantly.

In the lambda-to-delegate conversion, you do control the thing being assigned. There is nothing stopping you from making it an exact match in the parameter types and therefore we require you to. No fudging allowed here.