2010-12-08 65 views
1

我有以下幾點:通用構造可能很愚蠢的問題

GenericClass<T> : Class 
{ 
    T Results {get; protected set;} 
    public GenericClass<T> (T results, Int32 id) : base (id) 
    { 
    Results=results; 
    } 
    public static GenericClass<T> Something (Int32 id) 
    { 
    return new GenericClass<T> (i need to pass something like new T?, id); 
    } 
} 

更新T可以是任何類型或值,因此,使用新的()是okish對於某些類型的,但definetely不是值。我想這意味着一些課程重新設計。

想法是如何使用構造函數?例如,是否有可能傳遞類似於新T的東西(儘管它不應該,因爲T當時不知道),或者將會避免傳遞null的扭曲是什麼?

+0

根本不笨。你應該看到**在這裏發佈的一些**問題> ;-) – smirkingman 2010-12-09 16:14:08

回答

1
class GenericClass<T> : Class where T : new() 
{ 
    public T Results {get; protected set;} 
    public GenericClass (T results, Int32 id) : base (id) 
    { 
    Results=results; 
    } 
    public static GenericClass<T> Something (Int32 id) 
    { 
    return new GenericClass<T> (new T(), id); 
    } 
} 
3

這應該工作:

GenericClass<T> : Class where T : new() 
{ 
    T Results {get; protected set;} 
    public GenericClass<T> (T results, Int32 id) 
    { 
    Results=results; 
    } 
    public GenericClass<T> Something (Int32 id) : this(new T(), id) 
    { } 
} 
+0

正是我要說的,你打敗了我。對於OP,基本上你只需要將T限制爲具有已知公共構造函數的類(這裏是默認構造函數)。 – KeithS 2010-12-08 17:46:05

0

關於使用反射如何?

public static GenericClass<T> Something (Int32 id) 
    { 
    return new GenericClass<T> ((T)Activator.CreateInstance(typeof(T)), id); 
    } 
+0

WAY在頂部,儘管如此編譯它仍然會在運行時失敗,如果T沒有公共無參數構造函數。 – KeithS 2010-12-08 18:23:01