c# - 即使签名匹配,也无法将一种类型的委托(delegate)分配给另一种

标签 c# lambda delegates type-conversion func

我病态的好奇心让我想知道为什么以下失败:

// 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!

最佳答案

C# 对“结构”类型的支持非常有限。特别是,您不能简单地从一种委托(delegate)类型转换为另一种委托(delegate)类型,因为它们的声明是相似的。

来自语言规范:

Delegate types in C# are name equivalent, not structurally equivalent. Specifically, two different delegate types that have the same parameter lists and return type are considered different delegate types.

尝试其中之一:

// C# 2, 3, 4 (C# 1 doesn't come into it because of generics)
BinaryOperation b1 = new BinaryOperation(addThem);

// C# 3, 4
BinaryOperation b1 = (x, y) => addThem(x, y);
var b1 = new BinaryOperation(addThem);

关于c# - 即使签名匹配,也无法将一种类型的委托(delegate)分配给另一种,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4467412/

相关文章:

java - 发生异常时如何定位lambda?

c# - Lambda表达式-如果不存在则添加到集合

c# - 在 C# 的同一类中的另一个委托(delegate)函数中使用两个委托(delegate)函数的返回 View

ios - id delegate unrecognized selector 发送到实例

c# - 多线程访问MapPoint?

c# - Xamarin:适用于 Android 和 Windows UWP 的 Xamarin 表单中分组列表的垂直字母索引(跳转列表)

C# ThreadStatic + volatile 成员未按预期工作

c# - 如何将 C# SSLStream 客户端连接到 OpenSSL 服务器?

python - 使用过滤器忽略空/空白单元格

c# - 创建没有委托(delegate)的线程 - 为什么这有效?