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# のデリゲート型は名前が同等であり、構造的に同等ではありません。具体的には、同じパラメーター リストと戻り値の型を持つ 2 つの異なるデリゲート型は、異なるデリゲート型と見なされます。

次のいずれかを試してください。

// 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 に答える