簡體   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