代码之家  ›  专栏  ›  技术社区  ›  kpollock

作为基类型c#2.0的集合的集合

  •  2
  • kpollock  · 技术社区  · 16 年前

    我知道 Passing a generic collection of objects to a method that requires a collection of the base type

    它必须是引用相等的,即列表的副本不起作用。

    要重新迭代-我不能返回 新的 列表-必须是相同的列表

    3 回复  |  直到 9 年前
        1
  •  0
  •   Winston Smith    16 年前

    你想要:

    List<T>.ConvertAll()
    

    See here 更多信息。

        2
  •  8
  •   Eric Lippert    16 年前

    你没有。

    在C#2和C#3中,不可能有引用相等和改变元素类型。

    IEnumerable<T> , 在…上 IList<T> List<T> . 只有当源和目标T类型为引用类型时,协变转换才合法。简言之:

    List<Mammal> myMammals = whatever;
    List<Animal> x0 = myMammals; // never legal
    IEnumerable<Mammal> x1 = myMammals; // legal in C# 2, 3, 4
    IEnumerable<Animal> x2 = myMammals; // legal in C# 4, not in C# 2 or 3
    IEnumerable<Giraffe> x3 = myMammals; // never legal
    IList<Mammal> x4 = myMammals; // legal in C# 2, 3, 4
    IList<Animal> x5 = myMammals; // never legal
    IList<Giraffe> x6 = myMammals; // never legal
    List<int> myInts = whatever;
    IEnumerable<int> x7 = myInts; // legal
    IEnumerable<object> x8 = myInts; // never legal; int is not a reference type
    
        3
  •  1
  •   Josh    16 年前

    埃里克说得对。他的回答应该是公认的。不过,我还要补充一个建议。如果它是您的集合(例如,您可以修改集合类),那么您可以实现IEnumerable(WhateverBase的),即使您的集合是从集合(Whatever的)派生的。

    事实上,您也可以实现IList(WhateverBase的)、ICollection(WhateverBase的)等,例如,如果您在Add方法中得到不兼容的类型,则会抛出运行时异常。

    class GiraffeCollection : Collection<Giraffe>, IEnumerable<Animal> {
    
        IEnumerator<Animal> IEnumerable<Animal>.GetEnumerator() {
            foreach (Giraffe item in this) {
                yield return item;
            }
        }
    
    }