简体   繁体   English

C#:方法的通用实现不满足接口

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

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 anticipated 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.. 使用virtual关键字并将您的界面放在具体实现上。

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>
{

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM