即使签名匹配,也无法将一种类型的委托分配给另一种类型

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

// declared somewhere public delegate int BinaryOperation(int a, int b); // ... in a method body Func addThem = (x, y) => x + y; BinaryOperation b1 = addThem; // doesn't compile, and casting doesn't compile BinaryOperation b2 = (x, y) => x + y; // compiles! 

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); 

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

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

在这种情况下,演员阵容看起来不那么自然,但这也是同样的原因。