Pass An Instantiated System.Type as a Type Parameter for a Generic Class

后端 未结 6 1161
萌比男神i
萌比男神i 2020-11-21 07:46

The title is kind of obscure. What I want to know is if this is possible:

string typeName = ;
Type myType = Type.GetType(         


        
6条回答
  •  南方客
    南方客 (楼主)
    2020-11-21 08:08

    You can't do this without reflection. However, you can do it with reflection. Here's a complete example:

    using System;
    using System.Reflection;
    
    public class Generic
    {
        public Generic()
        {
            Console.WriteLine("T={0}", typeof(T));
        }
    }
    
    class Test
    {
        static void Main()
        {
            string typeName = "System.String";
            Type typeArgument = Type.GetType(typeName);
    
            Type genericClass = typeof(Generic<>);
            // MakeGenericType is badly named
            Type constructedClass = genericClass.MakeGenericType(typeArgument);
    
            object created = Activator.CreateInstance(constructedClass);
        }
    }
    

    Note: if your generic class accepts multiple types, you must include the commas when you omit the type names, for example:

    Type genericClass = typeof(IReadOnlyDictionary<,>);
    Type constructedClass = genericClass.MakeGenericType(typeArgument1, typeArgument2);
    

提交回复
热议问题