为什么Visual Studio在下面的父类中找不到T?
class Parent
{
private List<Object> _myChildList;
public Parent(Type T) {
_myChildList = new List(T);
}
}
class Child : Parent
{
public Child(): base(typeof(SomeClass)) {
}
}
您尝试做的是继承泛型类型,这不会通过构造函数,也不需要 Type 对象。这要简单得多:将基类创建为泛型类,然后从特定的类型化版本继承:
class Parent<T>
{
private List<T> _myChildList;
public Parent() {
_myChildList = new List<T>();
}
}
class Child : Parent<SomeClass>
{
public Child() {}
}
原始代码不起作用的原因是您的new List(T)
无效,原因有两个:
- 您将_myChildList定义为
List<object>
。即使你的语法是正确的,并且你创建了一个List<SomeClass>
,编译器也会抱怨List<object>
和List<SomeClass>
是不同的。他们是。 - 泛型是一种编译类型构造。当你将一个类定义为
Parent<SomeClass>
时,编译器需要提前知道SomeClass
是什么。 但是,Type
对象用于在运行时查询类型信息。因此,如果您有Type
对象,则无法创建该类型描述的类型的列表,除非使用 Reflection,反射是一种显式设计用于在运行时执行通常在编译时编码的操作的机制。
如果你不想知道编译时的类型,你可以试试这个:
class Parent
{
private System.Collections.IList _myChildList;
public Parent(Type T)
{
Type listType = typeof(List<>);
Type genericListType = listType.MakeGenericType(T);
_myChildList = (System.Collections.IList)Activator.CreateInstance(genericListType);
}
}
class Child : Parent
{
public Child()
: base(typeof(SomeClass))
{
}
}
我真的建议您使用标准泛型,因为这种方法在性能方面可能成本更高。