我病态的好奇心使我想知道为什么以下情况会失败:

// 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)类型。

根据语言规范:



尝试以下方法之一:

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

10-11 03:52