zoukankan      html  css  js  c++  java
  • Why IEnumerable<T> is defined as IEnumerable<out T>, not IEnumerable<T>

    http://stackoverflow.com/questions/12424537/why-ienumerablet-is-defined-as-ienumerableout-t-not-ienumerablet

    The out type parameter specifier denotes covariance.

    In practice,

    If I define two interfaces.

    ISomeInterface<T>{}

    ISomeCovariantInterface<out T>{}

    Then, I implement them like this.

    SomeClass<T>:ISomeInterface<T>,ISomeCovariantInterface<T>{}

    Then I try to compile this code,

    ISomeCovariantInterface<object>=newSomeClass<string>();// works

    ISomeInterface<object>=newSomeClass<string>();// fails

    The is because the covariant interface allows more derived instances, where as, the standard interface does not.

        public interface ISomeInterface<T> { }
    
        public interface ISomeCovariantInterface<out T> { }
    
        public class SomeClass<T> : ISomeInterface<T>, ISomeCovariantInterface<T> { }
    
                var obj = new SomeClass<string>();
    
                ISomeCovariantInterface<object> obj1 = obj;// works
                ISomeCovariantInterface<string> obj2 = obj;// works
                ISomeInterface<string> obj3 = obj;//work
                //ISomeInterface<object> obj4 = obj;//不可编译
    ----------------------------------- http://www.cnblogs.com/rock_chen/
  • 相关阅读:
    ValueStack、ActionContext
    s debug
    1923: [Sdoi2010]外星千足虫
    1013: [JSOI2008]球形空间产生器sphere
    HDU 3923 Invoker
    poj 1286 Necklace of Beads
    HDU 3037:Saving Beans
    2440: [中山市选2011]完全平方数
    1101: [POI2007]Zap
    1968: [Ahoi2005]COMMON 约数研究
  • 原文地址:https://www.cnblogs.com/rock_chen/p/3083257.html
Copyright © 2011-2022 走看看