有点困惑,我有一个通用类
public abstract class MyClass<T> : UserControl
{
}
我有一个这样的类型
Type type = Type.GetType("Type From DB as String", true, true);
我想使用类型创建 MyClass 的实例...但这不起作用。
MyClass<type> control = (MyClass<type>)LoadControl("/UsercControl.ascx");
有什么想法吗????
最佳答案
像这样:
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);
现在您将无法使用它作为 MyClass<T>
在调用方法方面,因为你不知道 T
...但是您可以使用一些不需要 T
的方法定义非泛型基类或接口(interface),并投向那个。或者您可以通过反射调用它的方法。
关于c# - 通用类和 Type.GetType(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3788225/