我有几个继承类,像这样一个抽象类:使用继承类型的C#集合泛型参数
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
的元素,但出现以下错误(CS1503和CS1950):
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
由于3210是SomeBaseType
,我应该可以做到这一点,对吧?这基本上与向IList<object>
添加一些任意的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
};
}
这是协方差和协方差泛型类不起作用,至少读一次长颈鹿。 – Rahul
每天都会问这个问题。再一次:长颈鹿列表不是动物列表。为什么?因为你可以将一只老虎放入动物列表中,但不能放入长颈鹿列表中。动物列表不是长颈鹿列表。为什么?因为动物列表中可能已经有一只老虎。因此,长颈鹿列表和动物列表从不兼容,因为您可以在这两种类型上执行的操作不同。有些动物是长颈鹿的事实是无关紧要的。 –