为什么下不编译? (包括仿制药和继承在C#) [英] Why does the following doesn't compile? (involves generics and inheritance in c#)
本文介绍了为什么下不编译? (包括仿制药和继承在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
}
}
是什么原因?
What's the reason?
推荐答案
差异存在于C#4.0打靶.NET 4中),但在限于接口和的使用/
退出
(哦,和引用类型的数组)。例如,为了使一个协变序列:
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.
这篇关于为什么下不编译? (包括仿制药和继承在C#)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文