为什么不编译以下内容?(涉及C#中的泛型和继承)
问题描述:
编译如下:
This compiles:
class ReplicatedBaseType
{
}
class NewType: ReplicatedBaseType
{
}
class Document
{
ReplicatedBaseType BaseObject;
Document()
{
BaseObject = new NewType();
}
}
但这不是:
class DalBase<T> : where T: ReplicatedBaseType
{
}
class DocumentTemplate
{
DalBase<ReplicatedBaseType> BaseCollection;
DocumentTemplate ()
{
BaseCollection= new DalBase<NewType>(); // Error in this line. It seems this is not possible
}
}
这是什么原因?
答
针对.NET 4的C#4.0中存在差异,但仅限于 in
/ out
(哦,还有引用类型的数组).例如,要创建协变序列:
Variance exists in C# 4.0 targetting .NET 4), but is limited to interfaces and usage of in
/out
(oh, and arrays of reference-types). For example, to make a covariant sequence:
class DalBase<T> : IEnumerable<T> where T: ReplicatedBaseType
{
public IEnumerator<T> GetEnumerator() {throw new NotImplementedException();}
IEnumerator IEnumerable.GetEnumerator() { throw new NotImplementedException(); }
}
class DocumentTemplate
{
IEnumerable<ReplicatedBaseType> BaseCollection;
DocumentTemplate()
{
BaseCollection = new DalBase<NewType>(); // Error in this line. It seems this is not possible
}
}
但除此之外...不.坚持使用非通用列表( IList
),或使用预期的列表类型.
But other than that... no. Stick to either non-generic lists (IList
), or use the expected list type.