2010-12-08 66 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