下面的第二個測試方法不能編譯(不能將lambda表達式轉換爲目標類型D1
)。這是否意味着(非泛型)委託逆轉不適用於lambda表達式?C#委託與lambda表達式的轉換
[TestFixture]
public class MyVarianceTests
{
private abstract class Animal {}
private class Tiger : Animal {}
private delegate Type D1(Tiger tiger);
private static Type M1(Animal animal)
{
return animal.GetType();
}
[Test]
public void ContravariantDelegateWithMethod()
{
D1 func = M1;
Type result = func(new Tiger());
Assert.AreEqual(result, typeof (Tiger));
}
[Test]
public void ContravariantDelegateWithLambda()
{
D1 func = (Animal animal) => animal.GetType();
Type result = func(new Tiger());
Assert.AreEqual(result, typeof (Tiger));
}
}
謝謝,這是我正在尋找的參考。而你對於爲什麼存在不一致的猜測對我來說也是有意義的。 – mtraudt