为什么在参数中声明类型参数 T 时无法识别



为什么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)无效,原因有两个:

  1. 您将_myChildList定义为List<object> 。即使你的语法是正确的,并且你创建了一个List<SomeClass>,编译器也会抱怨List<object>List<SomeClass>是不同的。他们是。
  2. 泛型是一种编译类型构造。当你将一个类定义为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))
    {

    }
}

我真的建议您使用标准泛型,因为这种方法在性能方面可能成本更高。

最新更新