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

时间:2014-04-05 13:47:59

标签: c# .net

为什么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)) {



    }
}

2 个答案:

答案 0 :(得分:4)

您要做的是继承泛型类型,而不是通过构造函数,或者需要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,这是一种显式设计为在运行时执行的机制,通常在编译时编码-time。

答案 1 :(得分:3)

如果您不想在编译时知道类型,可以试试这个:

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))
    {



    }
}

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