下面的第二种测试方法无法编译(无法将 lambda 表达式转换为目标类型D1
)。这是否意味着(非泛型)委托逆变不适用于 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));
}
}