代码之家  ›  专栏  ›  技术社区  ›  David

C#:如何创建泛型超类,由非泛型子类扩展

  •  1
  • David  · 技术社区  · 14 年前

    我有一堆存储库类,它们看起来都有点像下面的。请注意,我省略了某些方法;我只是想让您尝一尝。

    public class SuggestionRepository : ISuggestionRepository
    {
        private IUnitOfWork _unitOfWork;
    
        public SuggestionRepository(IUnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork;
        }
    
        public Suggestion Load(int id)
        {
            Suggestion suggestion;
            suggestion = _unitOfWork.Load<Suggestion>(id);
            return suggestion;
        }
    
        public IQueryable<Suggestion> All
        {
            get { return _unitOfWork.GetList<Suggestion>(); }
        }
    }

    您可以想象我的存储库之间重复代码的数量。

    我想创建一个Repository<T>类,它由我的存储库扩展,这样我就不必为每个存储库编写样板代码了。此类可能类似于以下内容:

    internal class Repository<T> where T : Entity
    {
        private IUnitOfWork _unitOfWork;
    
        internal Repository<T>(IUnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork;
        }
    
        public T Load(int id)
        {
            T t;
            t = _unitOfWork.Load<T>(id);
            return t;
        }
    
        public IQueryable<T> All
        {
            get { return _unitOfWork.GetList<T>(); }
        }
    }
    

    但是visualstudio并没有表现出任何爱。它在参数列表括号中表示“unexpected token”,表示它不能在静态上下文中访问非静态字段unitOfWork,并假装它不知道参数unitOfWork是什么。

    2 回复  |  直到 14 年前
        1
  •  1
  •   AakashM    14 年前

    泛型类的构造函数不应在方法名称中包含类型参数。简单地说

    internal Repository(IUnitOfWork unitOfWork)
    

        2
  •  0
  •   Dave D    14 年前

    您不能指定 <T> 在构造函数上,类对泛型类型进行操作这一事实暗示了这一点 T