11

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

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

2 回答 2

16

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

从语言规范:

C# 中的委托类型是名称等价的,而不是结构上等价的。具体来说,具有相同参数列表和返回类型的两种不同委托类型被视为不同的委托类型。

尝试以下之一:

// 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);
于 2010-12-17T03:33:47.583 回答
7

这是一个类似的问题:为什么不编译?

// declared somewhere
struct Foo {
    public int x;
    public int y;
}

struct Bar {
    public int x;
    public int y;
}

// ... in a method body
Foo item = new Foo { x = 1, y = 2 };

Bar b1 = item; // doesn't compile, and casting doesn't compile
Bar b2 = new Bar { x = 1, y = 2 }; // compiles!

在这种情况下,演员不工作似乎更自然一些,但实际上是相同的原因。

于 2010-12-17T05:21:23.967 回答