2015-11-08 196 views
1

我有一个基础通用类,看起来是这样的扩展限制:继承和泛型

public abstract class BaseTestDataEntity<T> 
     where T : IIdEntity, ICodeEntity, IActiveEntity, new() 
    { 
} 

这些接口代表了数据entities.This领域是非常有用的,因为使用这些接口,我可以写了通用基础类它可以有像添加,更新等方法。

但真正有用的是全面的设计时间支持基于接口的合同。

一个实例的一个例子:

public class Customer : BaseTestDataEntity<Customer> 
    {} 

现在我有一个情况,我想建立派生类BaseTestDataEntity的,其中将包括基地的所有约束(因此每个代码,T必须有ID,代码和活动标志)

但是,在派生类中,我想添加其他约束。

这样我就不必在BaseTestDataEntity中重复具体的方法。

我试图和我想做的事:

public class BaseTestDataEntityImpl<T> 
    : BaseTestDataEntity<T> where T : IIdEntity, ICodeEntity, IMultiTextEntity, IActiveEntity, new() 

    { 
     // This should enforce T constaints in the base class, but where do I put in new constraints in the derived T? 
    } 

回答

2

我不知道你实际上试图实现,但在你的代码中,所有的约束只影响衍生BaseTestDataEntityImpl<T>。他们没有通过继承链传递到BaseTestDataEntity

为了让更多的明确,让我们假设我有以下类:

public class FooHandler<T> where T : IFoo {} 

,现在我希望有另一个类继承FooHandler,但也需要它来实现IBar一般的参数。

public class FooAndBarHandler<TFooAndBar> where TFooAndBar : IFoo, IBar 

正如你所看到的,我甚至不同地命名了泛型参数,因为它们实际上是不同的。 TFooAndBar和它的约束与来自TFoo无关。您必须确保无论您传递给FooHandler是否实施了IFoo,这就是为什么TFooAndBar必须执行TFoo。但是还有其他的方法可以全面地填充这个基类通用约束。如果您认为以下情况:

interface IFoo {} 
interface IBar : IFoo {} 

你可以只写

public class BarHandler<TBar> : FooHandler<TBar> where TBar : IBar 

因为TBar : IBar约束已经迫使TBar,也能实现IFoo

或者你可以硬编码FooHandler<MyFooImplementation>

public class BarHandler<TBar> : FooHandler<MyFooImplementation> where TBar : IBar