Generic Class & Type.GetType()

前端 未结 4 1784
慢半拍i
慢半拍i 2021-02-14 11:54

Bit of a puzzler, I have a generic class

public abstract class MyClass : UserControl
{

}

and I have got a type like this

<         


        
4条回答
  •  终归单人心
    2021-02-14 12:19

    Something like this:

    Type typeArgument = Type.GetType("Type From DB as String", true, true);
    Type template = typeof(MyClass<>);
    Type genericType = template.MakeGenericType(typeArgument);
    object instance = Activator.CreateInstance(genericType);
    

    Now you won't be able to use that as a MyClass in terms of calling methods on it, because you don't know the T... but you could define a non-generic base class or interface with some methods in which don't require T, and cast to that. Or you could call the methods on it via reflection.

提交回复
热议问题