【问题标题】:Creating common base class implementing two generic interfaces?创建实现两个通用接口的通用基类?
【发布时间】:2013-03-23 04:46:27
【问题描述】:

有没有办法创建一个实现以下两个通用接口的基类?然后,这个基类将被“其他”类继承,这些类可以从两个接口中的任何一个调用方法。

public interface IGenericRepositoryOne<E> where E : Entity
{
    void Save(E entity);
    void Save(List<E> entityList);
    E Load(Guid entityId);
}

public interface IGenericRepositoryTwo<D, E> where E : Entity
{
    void Save(D dto);
    void Save(List<D> entityList);
    D Load(Guid entityId);
}

现在我们有两个独立的存储库,分别实现每个接口:

public abstract class RepositoryOne<D, E> : IGenericRepositoryOne<D, E> where E : Entity {...}

public abstract class RepositoryTWO<E> : IGenericRepositoryTwo<E> where E : Entity {...}

还有一些类需要继承RepositoryOneRepositoryTwo。正是在这些课程中,我希望做一些分解,例如:

public class MessageDataTypeRepository : RepositoryTwo<MyEntityType>
{
    // here when I call the method Load() I want it for RepositoryOne implementation.
}

public class MessageDataTypeRepository : RepositoryOne<MyDTOType, MyEntityType>
{
    // here when I call the method Load() I want it for the RepositoryTwo implementation.
}

【问题讨论】:

  • 你确定第二个的 吗?我在成员列表中没有看到 E。
  • 除此之外,您在尝试实现这两个接口时遇到了什么错误?它给你带来了哪些麻烦?
  • @AnthonyPegram:是的,我还需要E,因为还有其他操作使用它,为简洁起见,上面省略了。我更新了我的问题,以进一步阐明我想要做什么。

标签: c# architecture


【解决方案1】:

您可以实现这两个接口,也可以使用Explicit Interface Implementation 实现一个或两个。如果需要,这允许您为每个接口使用不同的实现。

如果这不是必需的,那么简单地实现两者应该很简单,因为就一种泛型类型而言,两个接口实际上是相同的:

public class Repository<D,E> : IGenericRepositoryOne<D>, IGenericRepositoryTwo<D,E> 
    where D : Entity
    where E : Entity
{
    void Save(D dto) {}
    void Save(List<D> entityList) {}
    D Load(Guid entityId)
    {
          // Implement...
    }
}

编辑:

针对您编辑的问题以及您的实际目标 -

这里的一个选择是不使用继承,而是使用组合。通过使用组合,您可以使您的“通用存储库”类公开一个单一的、有意义的接口,并在内部构建适当的存储库。然后,它可以根据需要将这些方法映射到适当的存储库。这将使您的存储库有效地成为Adapter Pattern 的实现,以使用通用接口包装任一存储库。

【讨论】:

  • 感谢这些 cmets。我进一步更新了我的问题以反映我想要完成的工作,如果可能的话,请你看看评论,否则我正在查看相同存储库的大量重复,几乎没有变化。
【解决方案2】:

是的,这是可能的,它被称为Explicit Interface Implementation

您可以使用一种方法从两个接口实现方法:

public void Save(D entity) { }

或单独实现:

public void IGenericRepositoryOne.Save(D entity) { }

public void IGenericRepositoryTwo.Save(D entity) { }

【讨论】:

    猜你喜欢
    • 2015-12-25
    • 1970-01-01
    • 1970-01-01
    • 2022-11-18
    • 2022-11-28
    • 1970-01-01
    • 2019-05-27
    • 1970-01-01
    • 2012-07-24
    相关资源
    最近更新 更多