2017-08-24 88 views
1

我想重載一個構造函數,除了默認的構造函數,它只會被調用類型int。我得到的最接近的是this重載通用類的構造函數,基於類型

如果不可能,爲什麼?

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 
    } 
} 
+1

你不能真正做到這一點,這是一個有點代碼味道的了。 – DavidG

回答

7

這是不可能超載基於通用類型的構造函數(或任何方法) - 但是你可以創建一個工廠方法

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

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

的短,你必須使用反射檢查共享構造函數中的泛型類型並分支代碼,這相當難看。

3

你可以找到通過型式,如果它的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 
}