Generic Class & Type.GetType()

前端 未结 4 1771
慢半拍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:03

    Generics in reflection are a bit more complex than this. What you're looking for are the GetGenericTypeDefinition() and MakeGenericType() methods. Take your generic type (you can get it by calling GetType() on an instance, or using typeof(MyClass<Object>)), and call GetGenericTypeDefinition() to get the basic, open generic type (MyClass<T>). Then, on that type, call MakeGenericType() and pass it an array with one element; the type you want to use to close the generic. That will get you a generic type closed with your dynamically discovered type (MyClass<MyType>), which you can pass to Activator.CreateInstance().

    0 讨论(0)
  • 2021-02-14 12:05

    You must construct the class via reflection.

    See http://msdn.microsoft.com/en-us/library/b8ytshk6.aspx for more details.

    0 讨论(0)
  • 2021-02-14 12:14

    You create new objects using reflection:

    type.GetConstructor(new Type[]{}).Invoke(new object[]{});
    
    0 讨论(0)
  • 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<T> 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.

    0 讨论(0)
提交回复
热议问题