Class <t,c>和Activator.CreateInstance </t,c>

时间:2011-09-27 06:38:36

标签: 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>();
    }
}

我正试图通过这样做来实现这个类的对象:

            Type type = typeof(MyClass<,>).MakeGenericType(typeOfSomeTClass, typeOfSomeCClass);
            object instance = Activator.CreateInstance(type);

我得到的只是System.MissingMethodException(此对象没有no-arg构造函数)...

我的代码出了什么问题?

2 个答案:

答案 0 :(得分:8)

听起来typeOfSomeTClasstypeOfSomeCClass是一种没有公共无参数构造函数的类型,如下所示:

this.t = Activator.CreateInstance<T>();
this.c = Activator.CreateInstance<C>();

您可以通过约束来强制执行此操作:

where T : SomeTClass, new()
where C : SomeCClass, new()

在这种情况下你也可以这样做:

this.t = new T();
this.c = new C();

答案 1 :(得分:0)

MakeGenericType应该在此上下文中使用Type数组。

请参阅http://msdn.microsoft.com/en-us/library/system.type.makegenerictype.aspx

例如

Type type = typeof(LigneGrille&lt;,&gt;)。MakeGenericType(new Type [] {typeOfSomeTClass,typeOfSomeCClass});