从继承的子类型自动T的基类泛型类

时间:2015-08-20 17:59:37

标签: c# generics inheritance

我有这种情况

abstract class Foo<T>
{
    // Implementation using T type...
}
class Bar : Foo<Bar>
{ }

从Foo继承的每个类都将自己用作泛型类型,并且我有各种继承类,例如:&#34; Bar1&#34;,&#34; Bar2&#34;等...

是否可以实现Foo类从继承的类类型中自动获取泛型类型?

2 个答案:

答案 0 :(得分:3)

如果您想约束 T以便每个继承者都是Foo<T>,那么您可以这样做:

abstract class Foo<T> where T:Foo<T>
{
    // Implementation using T type...
}
class Bar : Foo<Bar>
{ }

请注意,从S继承的任何课程Foo并非100%保证是Foo<S>,因为您仍可以这样做:

class Quux : Foo<Bar>
{ }

仍然满足通用约束,因为BarFoo<Bar>,但是Quux 不是 a Foo<Quux>

答案 1 :(得分:0)

如果这是一个常见的实现,那么是的。如果各种类型的实现不同,那么没有。

对于常见实现,只需按照模板方法模式将常见行为放在抽象基类中。

abstract class Foo<T>
{
    public void DoStuff(T obj)
    {
       ...implementation...
    }
}