开发者

Generic T get type from class

How can开发者_如何学Python I get this to work? var x = error type or namespace name expected.

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 (i.e. they have to be hardcoded), while in your case the result of j.GetType() can only be known at run time.

Generics are designed to provide compile-type safety, so this restriction cannot be lifted. It can be worked around in some cases, e.g. 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


Because generics must be known at compile time. In List<T>, T must be a constant type, for example List<Person>.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜