Cannot assign a delegate of one type to another even though signature matches

青春壹個敷衍的年華 提交于 2019-11-29 03:44:43

问题


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!

回答1:


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:

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.

Try one of:

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



回答2:


Here's a similar question: why doesn't this compile?

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

In this case it seems a little more natural for the cast to not work, but it's really the same reason.



来源:https://stackoverflow.com/questions/4467412/cannot-assign-a-delegate-of-one-type-to-another-even-though-signature-matches

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!