3 回答
TA贡献1842条经验 获得超21个赞
// Contravariance
interface IGobbler<in T> {
void gobble(T t);
}
// Since a QuadrupedGobbler can gobble any four-footed
// creature, it is OK to treat it as a donkey gobbler.
IGobbler<Donkey> dg = new QuadrupedGobbler();
dg.gobble(MyDonkey());
// Covariance
interface ISpewer<out T> {
T spew();
}
// A MouseSpewer obviously spews rodents (all mice are
// rodents), so we can treat it as a rodent spewer.
ISpewer<Rodent> rs = new MouseSpewer();
Rodent r = rs.spew();
为了完整......
// Invariance
interface IHat<T> {
void hide(T t);
T pull();
}
// A RabbitHat…
IHat<Rabbit> rHat = RabbitHat();
// …cannot be treated covariantly as a mammal hat…
IHat<Mammal> mHat = rHat; // Compiler error
// …because…
mHat.hide(new Dolphin()); // Hide a dolphin in a rabbit hat??
// It also cannot be treated contravariantly as a cottontail hat…
IHat<CottonTail> cHat = rHat; // Compiler error
// …because…
rHat.hide(new MarshRabbit());
cHat.pull(); // Pull a marsh rabbit out of a cottontail hat??
TA贡献1799条经验 获得超8个赞
这是我放在一起帮助我理解差异的原因
public interface ICovariant<out T> { }public interface IContravariant<in T> { }public class Covariant<T> : ICovariant<T> { }public class Contravariant<T> : IContravariant<T> { }public class Fruit { }public class Apple : Fruit { }public class TheInsAndOuts{ public void Covariance() { ICovariant<Fruit> fruit = new Covariant<Fruit>(); ICovariant<Apple> apple = new Covariant<Apple>(); Covariant(fruit); Covariant(apple); //apple is being upcasted to fruit, without the out keyword this will not compile } public void Contravariance() { IContravariant<Fruit> fruit = new Contravariant<Fruit>(); IContravariant<Apple> apple = new Contravariant<Apple>(); Contravariant(fruit); //fruit is being downcasted to apple, without the in keyword this will not compile Contravariant(apple); } public void Covariant(ICovariant<Fruit> fruit) { } public void Contravariant(IContravariant<Apple> apple) { }}
tldr
ICovariant<Fruit> apple = new Covariant<Apple>(); //because it's covariantIContravariant<Apple> fruit = new Contravariant<Fruit>(); //because it's contravariant
- 3 回答
- 0 关注
- 371 浏览
添加回答
举报