繁体   English   中英

Class <T,C>和Activator.CreateInstance

[英]Class<T,C> and 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 (此对象没有no-arg构造函数)...

我的代码出了什么问题?

听起来像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();

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

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

例如

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM