即使签名匹配,也无法将一种类型的委托分配给另一种类型
我病态的好奇心让我想知道为什么以下失败:
// declared somewhere
public delegate int BinaryOperation(int a, int b);
// ... in a method body
Func<int, int, int> addThem = (x, y) => x + y;
BinaryOperation b1 = addThem; // doesn't compile, and casting doesn't compile
BinaryOperation b2 = (x, y) => x + y; // compiles!
My morbid curiosity has me wondering why the following fails:
// declared somewhere
public delegate int BinaryOperation(int a, int b);
// ... in a method body
Func<int, int, int> addThem = (x, y) => x + y;
BinaryOperation b1 = addThem; // doesn't compile, and casting doesn't compile
BinaryOperation b2 = (x, y) => x + y; // compiles!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
C# 对“结构”类型的支持非常有限。特别是,您不能简单地从一种委托类型转换为另一种委托类型,因为它们的声明是相似的。
从语言规范来看:
尝试以下之一:
C# has very limited support for "structural" typing. In particular, you can't cast from one delegate-type to another simply because their declarations are similar.
From the language specification:
Try one of:
这是一个类似的问题:为什么不能编译?
在这种情况下,演员阵容不工作似乎更自然一些,但实际上是同样的原因。
Here's a similar question: why doesn't this compile?
In this case it seems a little more natural for the cast to not work, but it's really the same reason.