开发者

C#: Generic implementation of method doesn't satisfy interface

开发者 https://www.devze.com 2023-01-13 23:25 出处:网络
In this post I talked about using a generic base class to enable me to create repository classes without duplicating loads of basic plumbing code.

In this post I talked about using a generic base class to enable me to create repository classes without duplicating loads of basic plumbing code.

Each Repository is accessed through an interface. In the code below, I will only show one of the methods for the sake of brevity:

Interface:

IQueryable<Suggestion> All { get; }

Generic base class

public IQueryable<T> All
    {
      get { return _unitOfWork.GetList<T>(); }
    }

Concrete class (implements the interface and extends the generic base class)

public IQueryable<Suggestion> All
    {
      get { return _unitOfWork.GetList<Suggestion>(); }
    }

I anticipat开发者_如何学编程ed that I would be able to simply strip the method out of the concrete class, and the compiler would use the generic base class implementation instead and work out that was intended to satisfy the interface. But no!

When I strip the method out I get the old 'does not implement interface member' error.

If I can't do this, have my efforts to use a generic base class not been pointless? Or is there a way around this?


Can you make the interface itself generic then implement a typed version in your concrete class?

public interface IRepository<T>
{
    List<T> All { get; }
}

public class Repository<T>
{
      public List<T> All 
      {
          get { return new List<T>(); }
      }
}

public class SuggestionRepository : Repository<Suggestion>, IRepository<Suggestion>
{ }

I'd still suggest using the generic interface since it will save you from repeating yourself, but this works too.

public interface ISuggestionRepository
{
    List<Suggestion> All { get; }
}

public class Repository<T>
{
      public List<T> All 
      {
          get { return new List<T>(); }
      }
}

public class SuggestionRepository : Repository<Suggestion>, ISuggestionRepository
{ }


Use the virtual keyword and put your interface on your concrete implementation..

public interface IMyInterface<T>
{
    IQueryable<T> All { get; }
}

public abstract class MyBaseClass<T> : IMyInterface<T>
{
    public virtual IQueryable<T> All
    {
        get { return _unitOfWork.GetList<T>(); ; }
    }
}

public class MyClass : MyBaseClass<Suggestion>, IMyInterface<Suggestion>
{

}
0

精彩评论

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

关注公众号