泛型T从类中获取类型

本文关键字:获取 取类型 泛型 | 更新日期: 2023-09-27 18:08:05

我怎么才能让这个工作?Var x =期望的错误类型或命名空间名称。

class Program
{
    static void Main(string[] args)
    {
        Person j = new John();
        var t = j.GetType();
        var x = new List<t>();
    }
}
class John : Person
{
}
class Person
{
    public string Name;
}

泛型T从类中获取类型

这样使用泛型是不可能的。泛型类和函数的所有类型参数都必须在编译时知道(即它们必须硬编码),而在您的情况下,j.GetType()的结果只能在运行时知道。

泛型的设计目的是提供编译类型安全,因此不能取消此限制。在某些情况下,这是可以解决的,例如,你可以调用一个泛型方法,其类型参数只有在编译时使用反射才知道,但这通常是你应该避免的。

你可以这样做,但你必须使用反射来做到这一点。

    static void Main(string[] args)
    {
        Person j = new John();
        var t = j.GetType();
        Type genType = Type.MakeGenericType(new Type[] { typeof(List<>) });
        IList x =  (IList) Activator.CreateInstance(genType, t);        
    }

或者简单地说:

    static void Main(string[] args)
    {
        Type genType = Type.MakeGenericType(new Type[] { typeof(List<>) });
        IList x =  (IList) Activator.CreateInstance(genType, typeof(John)); 
    }

你必须使用IList接口,因为你需要添加东西到列表

因为在编译时必须知道泛型。在List<T>中,T必须为常量类型,如List<Person>