为了账号安全,请及时绑定邮箱和手机立即绑定

协方差和逆变现实世界的例子

协方差和逆变现实世界的例子

C#
吃鸡游戏 2019-07-23 18:09:50
协方差和逆变现实世界的例子我在理解如何在现实世界中使用协方差和逆变时遇到了一些麻烦。到目前为止,我见过的唯一例子是同样的旧数组示例。object[] objectArray = new string[] { "string 1", "string 2" };很高兴看到一个允许我在开发过程中使用它的例子,如果我能看到它在其他地方使用的话。
查看完整描述

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


查看完整回答
反对 回复 2019-07-23
?
守着星空守着你

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


查看完整回答
反对 回复 2019-07-23
  • 3 回答
  • 0 关注
  • 371 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信