逆变的C#中的标志(即in
)是直观的只是眼前的水平。 ,当你做到e“接受”泛型类型参数的方法。然而,在内部,反转意味着关系(Q&A with an explanation)的反转,因此在IA
内使用in
使其与IB
不相容。
这个问题最好用一个例子来说明。考虑类Animal
及其派生类Tiger
。让我们还假设IB<T>
有一个方法void MethodB(T input)
,这是从IA
的Method
叫:
class A_Impl<T> : IA<T> {
T data;
public void Method(IB<TInput> entities) {
entities.MethodB(data);
}
}
声明IA<in TInput>
和IB<in TInput>
意味着你可以做
IA<Animal> aForAnimals = new A_Impl<Animal>();
IA<Tiger> aForTigers = aForAnimals;
IA<in TInput>
有需要IB<TInput>
的方法,我们可以这样称呼:
aForTigers.Method(new B_Impl<Tiger>());
这是一个问题,因为现在A_Impl<Animal>
会传递一个Animal
到MethodB
的接口,期望Tiger
。
你也没问题IB<out T>
,虽然 - 都与协方差和逆变:
public interface IB<out T> {
// ^^^
}
// This works
public interface IA<in TInput> {
void Method(IB<TInput> x);
}
// This works too
public interface IC<out TInput> {
void Method(IB<TInput> x);
}