抽象泛型类作为泛型约束

时间:2014-06-24 14:51:14

标签: c# generics repository abstract-class

我试图为我的查找对象创建一个通用存储库并写下:

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

ICan...是定义存储库的粒度操作的接口,这样我就可以使用组合来定义行为

我想仅为我的LookUp对象限制此接口,所以我使用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 key

的解决方案
public interface ILookupRepository<T, TkeyType> : 
    IDisposable, 
    ICanGetAll<T>,
    ICanGetById<T, TkeyType>
    where T : LookUpObject<T, TkeyType>
    where TkeyType : struct

2 个答案:

答案 0 :(得分:1)

正如Magus在评论中所说,你必须在接口定义中定义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

答案 1 :(得分:1)

我猜你想要这个。这基本上是TyCobb对T和T1结合的答案,但我也认为你想要TKeyType是struct,基于你对抽象类的约束,而不是它从字面上继承Type&#34; Type& #34;

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

现在,如果你的&#34; id&#34;和你的关键&#34;实际上是同一块数据,你甚至可能想要这样。这假设键的类型为&#34; int&#34;。

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