类别和 Activator.CreateInstance
这是一些类:
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>();
}
}
我试图通过这样做来实例化此类的对象:
Type type = typeof(MyClass<,>).MakeGenericType(typeOfSomeTClass, typeOfSomeCClass);
object instance = Activator.CreateInstance(type);
我得到的只是一个 System.MissingMethodException (该对象没有无参数构造函数)。我
的代码有什么问题吗?
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)...
What is wrong with my code?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
听起来
typeOfSomeTClass
或typeOfSomeCClass
是一种没有公共无参数构造函数的类型,按照以下要求:您可以通过约束强制执行:
在这种情况下,您可以然后也做:
It sounds like
typeOfSomeTClass
ortypeOfSomeCClass
is a type that doesn't have a public parameterless constructor, as required by:You could enforce that via a constraint:
in which case you can also then do:
MakeGenericType 在此上下文中应使用 Type 数组。
请参阅 http://msdn.microsoft.com/en-us/ library/system.type.makegenerictype.aspx
例如
Type type = typeof(LigneGrille<,>).MakeGenericType(new Type[] {typeOfSomeTClass, typeOfSomeCClass});
MakeGenericType should use an array of Type in this context.
See http://msdn.microsoft.com/en-us/library/system.type.makegenerictype.aspx
For example
Type type = typeof(LigneGrille<,>).MakeGenericType(new Type[] {typeOfSomeTClass, typeOfSomeCClass});