下面的第二个测试方法不能编译(不能将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