C#: How to create a generic superclass to be extended by non-generic subclasses

送分小仙女□ 提交于 2019-12-11 09:14:36

问题


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?


回答1:


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.




回答2:


You can't specify <T> on the constructor, it's implied by the fact that the class operates on generic type T



来源:https://stackoverflow.com/questions/3626328/c-how-to-create-a-generic-superclass-to-be-extended-by-non-generic-subclasses

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!