Fra*_*ois 6 c# reflection activator
这是一些课程:
public class MyClass<T, C> : IMyClass where T : SomeTClass
where C : SomeCClass
{
private T t;
private C c;
public MyClass()
{
this.t= Activator.CreateInstance<T>();
this.c= Activator.CreateInstance<C>();
}
}
Run Code Online (Sandbox Code Playgroud)
我试图通过这样做来实现这个类的对象:
Type type = typeof(MyClass<,>).MakeGenericType(typeOfSomeTClass, typeOfSomeCClass);
object instance = Activator.CreateInstance(type);
Run Code Online (Sandbox Code Playgroud)
我得到的只是一个System.MissingMethodException(这个对象没有no-arg构造函数)......
我的代码出了什么问题?
这听起来像typeOfSomeTClass或者typeOfSomeCClass是不具有公共参数的构造函数,所要求的类型:
this.t = Activator.CreateInstance<T>();
this.c = Activator.CreateInstance<C>();
Run Code Online (Sandbox Code Playgroud)
您可以通过约束强制执行:
where T : SomeTClass, new()
where C : SomeCClass, new()
Run Code Online (Sandbox Code Playgroud)
在这种情况下,你也可以这样做:
this.t = new T();
this.c = new C();
Run Code Online (Sandbox Code Playgroud)