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.
这篇关于无法分配以委托具有较少特定参数类型的匿名方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:无法分配以委托具有较少特定参数类型的匿名方法


- 如何用自己压缩一个 IEnumerable 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- WebMatrix WebSecurity PasswordSalt 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- 输入按键事件处理程序 2022-01-01
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01