gpt4 book ai didi

c# - 在以下情况下正确使用抽象类或接口(interface)

转载 作者:太空宇宙 更新时间:2023-11-03 21:29:49 26 4
gpt4 key购买 nike

我有不同类型的文档:DocumentCitizen、DocumentOther、DocumentResolution 等。每种文档类型也有相应的存储库:DocumentCitizenRepository、DocumentOtherRepository、DocumentResolutionRepository。所有存储库都有一个名为 Documents 的属性和一个名为 SaveDocument 的方法。下面以 DocumentCitizenRepository 的内容为例:

public class DocumentCitizenRepository{

EFDbContext context= new EFDbContext();//EFDbContext inherits DbContext
public IQueryable<DocumentCitizen> Documents{get{context.DocmentsFromCitizens}}
public void SaveDocument(DocumentCitizen doc)
{//omitted for brevity}
}

其他存储库的内容相似。因此,我希望所有存储库都扩展一个名为 Repository 的抽象类。我还为所有名为 Document 的文档类型定义了一个抽象类,内容为空:

public abstract class Document{}

public abstract class Repository{
public abstract IQueryable<Document>{get;}
public abstract void SaveDocument(Document doc)
}

但我收到有关无效或缺少覆盖的警告,因为编译器需要属性和方法的签名相同。要查看差异:

基础抽象类中的方法:

  public abstract void SaveDocument(Document doc)

以及继承类中的那个:

  public abstract void SaveDocument(DocumentCitizen doc)

所以我很困惑是否可以做我想做的事。你有什么想法吗?

最佳答案

最有可能的是,您甚至可以更进一步,创建一个完全通用的基础存储库:

public interface IRepository<T>
{
IQueryable<T> GetQueryable();
void Save(T item);
}

public abstract class BaseRepository<T> : IRepository<T>
{
public IQueryable<T> GetQueryable() { ... }
public void Save(T item) { ... }
}

您仍然会有特定的存储库接口(interface),允许您创建特定于实体的方法:

public interface IDocumentCitizenRepository : IRepository<DocumentCitizen>
{
// this interface has no extra methods, just the plain ol' CRUD
}

public interface IDocumentResolutionRepository : IRepository<DocumentResolution>
{
// this one can do additional stuff
void DoSomethingSpecial(DocumentResolution doc);
}

抽象基类用于重用通用功能:

// this class will inherit everything from the base abstact class
public class DocumentCitizenRepository
: BaseRepository<DocumentCitizen>, IDocumentCitizenRepository
{ }

// this class will inherit common methods from the base abstact class,
// and you will need to implement the rest manually
public class DocumentResolutionRepository
: BaseRepository<DocumentResolution>, IDocumentResolutionRepository
{
public void DoSomethingSpecial(DocumentResolution doc)
{
// you still need to code some specific stuff every once in a while
}
}

这通常与依赖注入(inject)一起使用,这样您就可以只在业务层使用接口(interface)而不用关心实际的实现:

var repo = container.Resolve<IDocumentCitizenRepository>();
repo.Save(doc);

最后一部分(依赖项注入(inject))最好在组合根中完成,这意味着直接在整个代码中使用容器(“服务定位器”模式)并不是抽象这些依赖项的理想方式。尝试组织您的类以通过构造函数接收存储库接口(interface),这将允许您在进行单元测试时轻松模拟每个存储库。

关于c# - 在以下情况下正确使用抽象类或接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24887551/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com