[英]Using inherited types with C# collection generic type parameters
我有一个抽象类,其中有一些继承类,例如:
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
由于FirstSpecificType
是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
};
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.