簡體   English   中英

獲取具體類型並創建接口類型參數的實例?

[英]Get a concrete type and create instance of interface type parameter?

假設我是construcor,

    public MyClass(Manager<Iinterface> manager)
    {
         // How can i get the type of Iinterface and then create an instance
    }

我可以使此構造函數通用嗎? 喜歡,

    public MyClass<T>(Manager<T> manager) where T is Iinterface
    {
         // How can i get the type of Iinterface and then create an instance
    }

您需要使用類本身而不是構造函數來定義它。 如果您不能使類本身具有通用性,則可以使用靜態“創建”方法來實現。 但是,可能存在將Manager<T>的實例傳遞給Manager<Iinterface> ,因為類不能是協變的。

public class MyClass
{
    public MyClass(Manager<Iinterface> manager) 
    {
        // How can i get the type of Iinterface and then create an instance
    }
    public static MyClass Create<T>(Manager<T> manager) where T : Iinterface, new()
    {
        Type tType = typeof(T);
        T tInstance = new T();

        return new MyClass([some parameters]);
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM