2010-12-08 3 views
1

나는 다음 있습니다. 나는 그것이 약간의 클래스 재 설계를 암시한다고 생각한다.일반적인 생성자 가능성이 매우 바보 같은 질문

아이디어는 생성자를 사용하는 방법 이었습니까? 예를 들어 새로운 T와 비슷한 것을 전달할 수 있습니까? (T는 그 당시에는 알 수 없기 때문에 가능하지는 않지만) 또는 null 전달을 피하는 비틀기는 무엇입니까?

+0

전혀 바보가 아닙니다. ** 여기에 게시 된 질문 중 일부 **가 표시되어야합니다. ;;-) – smirkingman

답변

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를 알려진 public 생성자 (여기서는 기본 생성자)가있는 클래스로 제한해야합니다. – KeithS

0

어떻게 반사를 사용하는 방법에 대해?

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

길 위에서, 그리고 T 컴파일러가 매개 변수없는 public 생성자를 가지고 있지 않다면 컴파일시에도 런타임에 여전히 실패 할 것이다. – KeithS