6

这是一些类:

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(这个对象没有无参数构造函数)......

我的代码有什么问题?

4

2 回答 2

8

这听起来像typeOfSomeTClassortypeOfSomeCClass是一种没有公共无参数构造函数的类型,如以下要求:

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();
于 2011-09-27T06:41:33.763 回答
0

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

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

例如

类型 type = typeof(LigneGrille<,>).MakeGenericType(new Type[] {typeOfSomeTClass, typeOfSomeCClass});

于 2011-09-27T06:47:50.517 回答