Generic Class&Type.GetType()

And*_*ndy 10 c# asp.net generics types

一点益智,我有一个通用类

public abstract class MyClass<T> : UserControl
{

}
Run Code Online (Sandbox Code Playgroud)

我有这样的类型

Type type = Type.GetType("Type From DB as String", true, true);
Run Code Online (Sandbox Code Playgroud)

我想创建和使用MyClass类型的实例......但是,这是行不通的.

MyClass<type> control = (MyClass<type>)LoadControl("/UsercControl.ascx");
Run Code Online (Sandbox Code Playgroud)

有任何想法吗????

Jon*_*eet 15

像这样的东西:

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);
Run Code Online (Sandbox Code Playgroud)

现在你将无法使用它作为MyClass<T>调用它的方法,因为你不知道T...但你可以定义一个非泛型基类或接口与一些方法不要求T,并投入到那.或者你可以通过反射调用它上面的方法.


Grz*_*nio 0

您使用反射创建新对象:

type.GetConstructor(new Type[]{}).Invoke(new object[]{});
Run Code Online (Sandbox Code Playgroud)