代码之家  ›  专栏  ›  技术社区  ›  Raj Rao

关于协方差的问题

  •  15
  • Raj Rao  · 技术社区  · 14 年前

    interface I1 { }
    class CI1: I1 { }
    
    List<CI1> listOfCI1 = new List<CI1>();
    
    IEnumerable<I1> enumerableOfI1 = listOfCI1; //this works
    
    IList<I1> listofI1 = listOfCI1; //this does not
    

    我可以将我的“列表”分配给 IEnumerable<I1> (由于协方差)

    但为什么我不能把它分配给 IList<I1> 为此,我甚至不能做以下事情:

    List<I1> listOfI12 = listOfCI1;
    

    4 回复  |  直到 14 年前
        1
  •  24
  •   Jon Skeet    7 年前

    简单地说, IList<T> 不是协变的,但是 IEnumerable<T>

    假设 IList<T> 协变的。下面的代码显然不是类型安全的。。。但你希望错误在哪里呢?

    IList<Apple> apples = new List<Apple>();
    IList<Fruit> fruitBasket = apples;
    fruitBasket.Add(new Banana()); // Aargh! Added a Banana to a bunch of Apples!
    Apple apple = apples[0]; // This should be okay, but wouldn't be
    

    太多了 blog post series 在上面,或者看着 video 我说的与国家数据中心的差异。

    IEnumerable<int> 进入之内 IEnumerable<object>

        2
  •  5
  •   Andrey    14 年前

    比较声明(msdn)

    public interface IEnumerable<out T> : IEnumerable
    
    public interface IList<T> : ICollection<T>, IEnumerable<T>, IEnumerable
    

    你看到那个神奇的词了吗 out ? 这意味着协方差是开的。

        3
  •  3
  •   SLaks    14 年前

    不。

    I1 只应包含 C1 s。

        4
  •  1
  •   Andrew Bezzub    14 年前

    IList<T> 接口不是协变的。