开发者

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

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:

开发者_如何学Gointernal 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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜