2014-06-24 252 views
0

IAM試圖創建一個通用存儲庫爲我查找對象,並寫:摘要泛型類的泛型約束

public interface ILookupRepository<T> : 
    IDisposable, 
    ICanGetAll<T>, 
    ICanGetById<T, int> 
    where T: LookUpObject 
{ 
} 

ICan...的接口定義粒狀操作庫,這樣我可以使用組合來定義行爲

我想限制這個接口只爲我查找對象,所以我用的是where T: LookUpObject約束

這是抽象類:

public abstract class LookUpObject<TObject, TKeyType> : IKeyedEntity<TKeyType> 
    where TObject : class 
    where TKeyType : struct 
{ 
    private TKeyType id; 
    private string description; 
    private bool valid; 
    public TKeyType Id 
    { 
     get { return id; } 
     set { id = value; } 
    } 
    public string Description 
    { 
     get { return description; } 
     set { description= value; } 
    } 
    public bool Valid 
    { 
     get { return valid; } 
     set { valid= value; } 
    } 
    protected LookUpObject() 
    {   
    } 
} 

,但我不知道如何在我的回購類中定義的約束:
我嘗試

public interface ILookupRepository<T> : 
    IDisposable, 
    ICanGetAll<T>, 
    ICanGetById<T, int> 
    where T: LookUpObject<T1, TkeyType> where T1: class 
     where TkeyType: Type 

,但它不承認T1TkeyType

是可能的事情?

編輯

溶液@Grax與TkeyType的不是int關鍵

public interface ILookupRepository<T, TkeyType> : 
    IDisposable, 
    ICanGetAll<T>, 
    ICanGetById<T, TkeyType> 
    where T : LookUpObject<T, TkeyType> 
    where TkeyType : struct 
+2

這可能只是'T1'和'TKeyType'需要在'ILookupRepository'上。不完全確定。 – Magus

回答

1

我猜你想要這個。這基本上是TyCobb用T和T1結合的答案,但我也認爲你希望TKeyType是結構體,基於你放在抽象類上的約束,而不是從字面類型「Type」繼承。

public interface ILookupRepository<T, TKeyType> : 
     IDisposable, 
     ICanGetAll<T>, 
     ICanGetById<T, int> 
     where T : LookUpObject<T, TKeyType> 
     where TKeyType : struct 
    { 
    } 

現在,如果你的「id」和你的「key」實際上是同一條數據,你甚至可能會這樣想。這假定密鑰將是「int」類型。

public interface ILookupRepository<T> : 
     IDisposable, 
     ICanGetAll<T>, 
     ICanGetById<T, int> 
     where T : LookUpObject<T, int> 
    { 
    } 
+0

猜測幾乎是正確的,也許我會將ICanGetById 轉換成ICanGetById 。明天在工作中,我會嘗試改變問題代碼 –

1

如法師在評論中指出,必須在接口定義來定義T1TKeyType這樣你就可以通過在類型中。

public interface ILookupRepository<T, T1, TkeyType> : 
    IDisposable, 
    ICanGetAll<T>, 
    ICanGetById<T, int> 
    where T: LookUpObject<T1, TkeyType> where T1: class 
     where TkeyType: Type 

所以,當你實現接口,傳遞什麼樣的類型有:

public MyPersonRepository : ILookupRepository<Person, MyT1Object, MyType> 

你的定義可能是正確的,但看你的代碼提供了什麼,好像你正在複製TT1。如果是這種情況,那麼請刪除T1,而不是使用T

+0

是的:T和T1是一樣的,我以爲我必須重新定義那 –