逆變的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);
}