创建实现两个通用接口的公共基类?

时间:2013-03-22 19:15:50

标签: c# architecture

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

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.
}

2 个答案:

答案 0 :(得分:3)

您可以实现这两个接口,并使用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的实现,以使用公共接口包装任一存储库。

答案 1 :(得分:2)

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

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

public void Save(D entity) { }

或单独实施:

public void IGenericRepositoryOne.Save(D entity) { }

public void IGenericRepositoryTwo.Save(D entity) { }
相关问题