gpt4 book ai didi

c# - 协变和逆变现实世界的例子

转载 作者:IT王子 更新时间:2023-10-29 03:31:49 24 4
gpt4 key购买 nike

我在理解如何在现实世界中使用协变和逆变时遇到了一些困难。

到目前为止,我见过的唯一示例是相同的旧数组示例。

object[] objectArray = new string[] { "string 1", "string 2" };

如果我能看到它在其他地方使用,那么很高兴看到一个允许我在开发过程中使用它的示例。

最佳答案

// 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??

关于c# - 协变和逆变现实世界的例子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2662369/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com