无法分配以委托具有较少特定参数类型的匿名方法 [英] Can’t assign to delegate an anonymous method with less specific parameter type

查看:14
本文介绍了无法分配以委托具有较少特定参数类型的匿名方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以分配一个方法 M 来委托对象 d 具有不太具体的参数类型,但是当我想分配一个具有相同签名的匿名方法时作为方法 Md,我得到一个错误.

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.

这是为什么呢?

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 当然是正确的,这是设计使然.

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.

在 lambda 到委托的转换中,您确实控制被分配的事物.没有什么阻止您使其与参数类型完全匹配,因此我们要求您这样做.这里不允许捏造.

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.

这篇关于无法分配以委托具有较少特定参数类型的匿名方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆