IRepository与IRepository <t> </t>

时间:2011-04-21 19:26:33

标签: .net generics repository

我正在尝试为我的所有存储库实现定义一个特定的接口,而不仅仅是这个:

public abstract class GeneralizedRepository
{
    readonly IDataModel _Model;

    public GeneralizedRepository(IDataModel Model) {
        if (Model == null)
            throw new NullReferenceException();
        _Model = Model;
    }

    public IDataModel DataModel { get { return _Model; } }

    public abstract IEnumerable<T> GetAll<T>();
    public abstract T GetOne<T>(Func<T, bool> predicate);

    public abstract bool Contains<T>(Func<T, bool> predicate);
    public abstract void Add<T>(T entity);
    public abstract void Update<T>(T entity);
    public abstract bool Remove<T>(Func<T, bool> predicate);
}

这是一个类,因为我的派生存储库具有共同的实例DataModel

现在我的具体实现如下:

public class DetailRep : GeneralizedRepository
{
    public DetailRep(IDataModel Model) : base(Model) { }
    public DetailRep(UnitOfWork Unit) : base(Unit.Model) { }

    public override IEnumerable<T> GetAll<T>() {
        throw new NotImplementedException();
    }

    public override T GetOne<T>(Func<T, bool> predicate) {
        throw new NotImplementedException();
    }

    public override bool Contains<T>(Func<T, bool> predicate) {
        throw new NotImplementedException();
    }

    public override void Add<T>(T entity) {
        throw new NotImplementedException();
    }

    public override void Update<T>(T entity) {
        throw new NotImplementedException();
    }

    public override bool Remove<T>(Func<T, bool> predicate) {
        throw new NotImplementedException();
    }
}

但它是明细存储库,我的意思是我想要替换所有 T 详细信息

但是在编译时会抛出一个错误:

类型参数声明必须是标识符而不是类型

1 个答案:

答案 0 :(得分:2)

将您的抽象类声明为通用:

public abstract class GeneralizedRepository<T>
{
    readonly IDataModel _model;
    public GeneralizedRepository(IDataModel model)
    {
        if (model == null)
            throw new NullReferenceException();
        _model = model;
    }
    public IDataModel DataModel { get { return _model; } }
    public abstract IEnumerable<T> GetAll();
    public abstract T GetOne(Func<T, bool> predicate);
    public abstract bool Contains(Func<T, bool> predicate);
    public abstract void Add(T entity);
    public abstract void Update(T entity);
    public abstract bool Remove(Func<T, bool> predicate);
}

与您的派生类相比,请使用Detail填写“类型”:

public class DetailRep  : GeneralizedRepository<Detail>
{
    public DetailRep(IDataModel model)
        : base(model)
    {
    }
    public override IEnumerable<Detail> GetAll(){}
    public override Detail GetOne(Func<Detail, bool> predicate){}
    public override bool Contains(Func<Detail, bool> predicate){}
    public override void Add(Detail entity){}
    public override void Update(Detail entity){}
    public override bool Remove(Func<Detail, bool> predicate){}
}