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

后端 未结 6 1169
萌比男神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:02

    My requirements were slightly different, but will hopefully help someone. I needed to read type from a config and instantiate the generic type dynamically.

    namespace GenericTest
    {
        public class Item
        {
        }
    }
    
    namespace GenericTest
    {
        public class GenericClass
        {
        }
    }
    

    Finally, here is how you call it. Define the type with a backtick.

    var t = Type.GetType("GenericTest.GenericClass`1[[GenericTest.Item, GenericTest]], GenericTest");
    var a = Activator.CreateInstance(t);
    

提交回复
热议问题