簡體   English   中英

重載泛型類的構造函數,基於類型

[英]Overload the Constructor of the generic class, Based on Type

我試圖重載默認構造函數之外的構造函數,只會調用int類型。 我得到的最接近的是這個

如果不可能,那為什么?

class Program
{
    static void Main()
    {
        //default construcotr get called
        var OGenerics_string = new Generics<string>();

        //how to make a different construcotr for type int
        var OGenerics_int = new Generics<int>();
    }

    class Generics<T>
    {
        public Generics()
        {
        }
        // create a constructor which will get called only for int
    }
}

根據泛型類型重載構造函數(或任何方法)是不可能的 - 但您可以創建工廠方法

class Generics<T>
{
    public Generics()
    {
    }

    public static Generics<int> CreateIntVersion()
    {
          /// create a Generics<int> here
    }
}

除此之外,你必須使用反射檢查共享構造函數中的泛型類型並分支代碼,這將是相當丑陋的。

你可以找到傳遞的類型,如果它的int - 做一些邏輯

void Main()
{
    new Generics<string>();
    new Generics<int>();
}

class Generics<T>
{
    public Generics()
    {
        if(typeof(T) == typeof(int)) InitForInt();
    }

    private void InitForInt()
    {
        Console.WriteLine("Int!");      
    }
    // create a constructor which will get called only for int
}

暫無
暫無

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

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