Can’t assign to delegate an anonymous method with less specific parameter type(无法分配以委托具有较少特定参数类型的匿名方法)
问题描述
我可以分配一个方法 M
来委托对象 d
具有不太具体的参数类型,但是当我想分配一个具有相同签名的匿名方法时作为方法 M
到 d
,我得到一个错误.
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.
这篇关于无法分配以委托具有较少特定参数类型的匿名方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:无法分配以委托具有较少特定参数类型的匿名方法
基础教程推荐
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- c# Math.Sqrt 实现 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 将 XML 转换为通用列表 2022-01-01