问题描述
我有一堆Repository类,它们看起来都像下面这样。请注意,我省略了某些方法;
public class SuggestionRepository:ISuggestionRepository
{
private IUnitOfWork _unitOfWork ;
public SuggestionRepository(IUnitOfWork unitOfWork)
{
_unitOfWork = unitOfWork;
}
public建议Load(int id)
{
建议提示;
suggestion = _unitOfWork.Load< Suggestion>(id);
返回建议;
}
public IQueryable< Suggestion>所有
{
获得{return _unitOfWork.GetList< Suggestion>(); }您可以想象我的代码库之间重复的代码数量是多少。
我想创建一个Repository< T>这个类是由我的仓库扩展的,所以希望我不必为每个代码编写样板代码。这个类可能如下所示:
内部类Repository< T>其中T:实体
{
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>所有
{
获得{return _unitOfWork.GetList< T>(); }
}
}
但是Visual Studio没有显示该构造函数爱一切。它会在参数列表括号内说'意外的令牌',表示它无法在静态上下文中访问非静态字段_unitOfWork,并假装它不知道参数unitOfWork是什么。
显然泛型类可以有构造函数,因为它有可能创建一个List< T>例如。那么发生了什么?
解决方案泛型类的构造函数不应该在方法名称中包含类型参数。简单地说:
内部版本库(IUnitOfWork unitOfWork)
,看看你是怎么过的。
I have a bunch of Repository classes which all look a bit like the following. Note that I have omitted certain methods; I just want you to get a flavour.
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>(); }
}
}
You'll imagine the amount of repeated code I have between my repositories.
I would like to create a Repository<T> class which is extended by my repositories so that hopefully I don't have to write boilerplate code for each one. This class might look something like the following:
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>(); }
}
}
But Visual Studio isn't showing that constructor any love at all. It's saying 'unexpected token' around the parameter list brackets, saying it can't access the non-static field _unitOfWork in a static context, and pretending it doesn't know what the parameter unitOfWork is.
Clearly generic classes can have constructors as it's possible to new up a List<T> for example. So what's going on?
解决方案 The constructor for a generic class should not have the type arguments in the method name. Simply say
internal Repository(IUnitOfWork unitOfWork)
and see how you get on.
这篇关于C#:如何创建一个通用的超类,以便通过非泛型子类进行扩展的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!