Generic Class & Type.GetType()

前端 未结 4 1782
慢半拍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)), and call GetGenericTypeDefinition() to get the basic, open generic type (MyClass). 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), which you can pass to Activator.CreateInstance().

    提交回复
    热议问题