简体   繁体   English

类的通用获取类型

[英]Generic T get type from class

How can I get this to work? 我该如何工作? var x = error type or namespace name expected. 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;
}

It is not possible to use generics like that. 不可能使用这样的泛型。 All type parameters of generic classes and functions have to be known at compile time (ie they have to be hardcoded), while in your case the result of j.GetType() can only be known at run time. 泛型类和函​​数的所有类型参数都必须在编译时已知(即必须进行硬编码),而在您的情况下, j.GetType()的结果只能在运行时知道。

Generics are designed to provide compile-type safety, so this restriction cannot be lifted. 泛型旨在提供编译类型的安全性,因此不能解除此限制。 It can be worked around in some cases, eg you can call a generic method with a type parameter that is only known at compile time using Reflection, but this is generally something you should avoid if possible. 在某些情况下可以解决该问题,例如,您可以使用反射类型调用仅在编译时才知道的类型参数的泛型方法,但是通常应避免这种情况。

You can do it, but you have to use reflection to do so. 您可以执行此操作,但是必须使用反射来执行此操作。

    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);        
    }

or really simply: 或者真的很简单:

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

You'll have to use the IList Interface as you need to add stuff to the list 您需要使用IList接口,因为您需要向列表中添加内容

Because generics must be known at compile time. 因为泛型必须在编译时就知道。 In List<T> , T must be a constant type, for example List<Person> . List<T> ,T必须是常量类型,例如List<Person>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM