2010-02-11 68 views
0

有沒有辦法做到這一點,而不使用Type類?我寧願使用泛型。反向泛型?

abstract class MyAbstract 
{ 
    protected abstract T GetSpecialType(); 

    private void MyPrivateFunction() 
    { 
     someT = GetSpecialType(); 

    } 
    private void DoSomething<T>() 
    { 
    } 
} 

class MyConcrete : MyAbstract 
{ 
    protected override T GetSpecialType() 
    { 
    return SomeReallySpecialClass(); 
    } 
} 

我確定這會工作(它現在的方式),但它的醜陋。

abstract class MyAbstract 
{ 
    protected abstract Type GetSpecialType(); 

    private void MyPrivateFunction() 
    { 
     Type someT = GetSpecialType(); 

    } 
    private void DoSomething(Type ofT) 
    { 
    } 
} 

class MyConcrete : MyAbstract 
{ 
    protected override Type GetSpecialType() 
    { 
    return typeof(SomeReallySpecialClas(); 
    } 
} 

我應該把它作爲抽象類中的泛型參數?

回答

2

這並不完全清楚你想要做什麼,但也許這樣?

abstract class MyAbstract<T> 
{ 
    private void DoSomething() 
    { 
     // Use typeof(T) here as needed 
    } 
} 

class MyConcrete : MyAbstract<SomeReallySpecialClass> 
{ 
    // Is there any other logic here? 
} 
+0

我在想這是最好的方法。 – 2010-02-11 18:36:09

0

我不能完全弄清楚你試圖實現什麼。 (如果我在錯誤的方向這個答案的標題,你可能想澄清你的問題了一下,加的是什麼,你正在嘗試做一些細節)


如果你只是想根據泛型類型參數創建新對象,您可能需要查看new constraint

class ItemFactory<T> where T : new() 
{ 
    public T GetNewItem() 
    { 
     return new T(); 
    } 
} 

通過包括「新」的約束它保證了創建ItemFactory類時提供的任何類型必須有一個公共的無參數的構造函數,這意味着你可以創建一個類裏面的新對象。