[英]Class<T,C> and Activator.CreateInstance
Here is some class: 这是一些课程:
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>();
}
}
And I'm trying to instanciate object of this class by doing this: 我试图通过这样做来实现这个类的对象:
Type type = typeof(MyClass<,>).MakeGenericType(typeOfSomeTClass, typeOfSomeCClass);
object instance = Activator.CreateInstance(type);
And all I get is a System.MissingMethodException
(there is no no-arg constructor for this object)... 我得到的只是一个
System.MissingMethodException
(此对象没有no-arg构造函数)...
What is wrong with my code? 我的代码出了什么问题?
It sounds like typeOfSomeTClass
or typeOfSomeCClass
is a type that doesn't have a public parameterless constructor, as required by: 听起来像
typeOfSomeTClass
或typeOfSomeCClass
是一个没有公共无参数构造函数的类型,如下所示:
this.t = Activator.CreateInstance<T>();
this.c = Activator.CreateInstance<C>();
You could enforce that via a constraint: 您可以通过约束强制执行:
where T : SomeTClass, new()
where C : SomeCClass, new()
in which case you can also then do: 在这种情况下,你也可以这样做:
this.t = new T();
this.c = new C();
MakeGenericType should use an array of Type in this context. MakeGenericType应在此上下文中使用Type数组。
See http://msdn.microsoft.com/en-us/library/system.type.makegenerictype.aspx 请参阅http://msdn.microsoft.com/en-us/library/system.type.makegenerictype.aspx
For example 例如
Type type = typeof(LigneGrille<,>).MakeGenericType(new Type[] {typeOfSomeTClass, typeOfSomeCClass}); 类型type = typeof(LigneGrille <,>)。MakeGenericType(new Type [] {typeOfSomeTClass,typeOfSomeCClass});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.