2014-06-24 146 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是一样的,我以为我必须重新定义那 –