2010-02-11 74 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类时提供的任何类型必须有一个公共的无参数的构造函数,这意味着你可以创建一个类里面的新对象。