使用带有C#集合泛型类型参数的继承类型

时间:2016-03-01 21:46:12

标签: c# .net generics inheritance

我有一个抽象类,有一些继承类,如:

internal abstract class SomeBaseType {}
internal class FirstSpecificType : SomeBaseType {}
internal class SecondSpecificType : SomeBaseType {}
internal class ThirdSpecificType : SomeBaseType {}

和具有约束泛型类型参数的类:

internal class SomeCollection<T> : ICollection<SomeDataStructure>
    where T : SomeBaseType {}

我创建了List<SomeCollection<SomeBaseType>>,并尝试添加SomeBaseType的各种继承类的元素,但我收到以下错误(CS1503CS1950):

Argument 1: cannot convert from 'Namespace.SomeCollection<FirstSpecificType>' to 'Namespace.SomeCollection<SomeBaseType>'
The best overloaded Add method 'List<SomeCollection<SomeBaseType>>.Add(SomeCollection<SomeBaseType>)' for the collection initializer has some invalid arguments

由于FirstSpecificTypeSomeBaseType,我应该可以这样做,对吧?它与向object添加一些IList<object>的任意一组基本相同。

对于其他上下文,此错误显示的代码如下所示:

protected Constructor()
{
    collectionOne = new SomeCollection<FirstSpecificType>();
    collectionTwo = new SomeCollection<SecondSpecificType>();
    collectionThree = new SomeCollection<ThirdSpecificType>();

    allCollections = new List<SomeCollection<SomeBaseType>>
    {
        // Each of these three collections has the error
        collectionOne,
        collectionTwo,
        collectionThree
    };
}

1 个答案:

答案 0 :(得分:1)

这是covariance and contravariance的问题,基本上说虽然 FirstSpecificType确实是SomeBaseType,但SomeCollection<FirstSpecificType> 严格来说不是 {{1 }}

Eric Lippert写了一些关于这个和长颈鹿的精彩articles,我建议大家至少阅读一次: - )