2015-11-08 259 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