c# - 我们可以使用抽象类而不是接口(interface)吗

标签 c# oop interface abstract-class

这个问题在这里已经有了答案:





Interface vs Abstract Class (general OO)

(35 个回答)


6年前关闭。




我已经开始了支持开发人员的职业生涯,但我梦想为 S/W 开发人员找到一份工作。
我正在用 C# 学习 OOPS。经常困扰我的一件事是接口(interface)和抽象类的使用。何时使用接口(interface),何时使用抽象类。我在谷歌上搜索这个主题,但无论我浏览什么答案,我看到所有人都试图解释什么是抽象和接口(interface),但我不是在他们的定义之后,而是我想看看他们在现实世界程序中的实际用法。在这里我想强调一个使用接口(interface)的代码,但我认为完整的东西也可以用抽象类来设计。

请参阅下面的存储库设计模式代码,其中使用了接口(interface)
如果我将存储库公开为接口(interface)

public interface IEmployeeRepository
{
    Employee[] GetAll();
}

那么优势将是我可以拥有尽可能多的实现,如下所示
public class EmployeeRepositoryEF: IEmployeeRepository
{
    public Employee[] GetAll()
    {
        //here you will return employees after querying your EF DbContext
    }
}

public class EmployeeRepositoryXML: IEmployeeRepository
{
    public Employee[] GetAll()
    {
        //here you will return employees after querying an XML file
    }
}

public class EmployeeRepositoryWCF: IEmployeeRepository
{
    public Employee[] GetAll()
    {
        //here you will return employees after querying some remote WCF service
    }
}

参见上面的代码,它有一种合约方法GetAll()以及谁会扩展接口(interface),然后他们可以提供自己的实现。这是优势,但我的问题是我可以在这里写抽象类而不是接口(interface)吗?

假设我有一个抽象类
abstract class AbsEmployeeRepository
{ 
   abstract public Employee[] GetAll(); 
}

现在我的所有其他存储库将扩展抽象类 AbsEmployeeRepository
并覆盖函数GetAll()给出自己的实现。

现在的问题是抽象类是否可以解决我的目的,那么为什么在这种情况下我们需要接口(interface)。在涉及多重继承的情况下,接口(interface)将是首选,否则我们可以使用抽象类完成工作。

寻找有值(value)的意见和建议。谢谢

最佳答案

您将使用 抽象类 , 当你有

  • 要共享的代码。
  • 方法中的默认行为,但希望您的类的用户能够覆盖它。

  • 您将使用 接口(interface)什么时候
  • 没有共享代码。
  • 它需要应用于许多对象,没有通用的基类。
  • 使公共(public)方法的定义更清晰并提供文档。
  • 您希望源代码是私有(private)的。

  • 通常你会使用一个抽象类(用于共享代码)和一个接口(interface)(用于文档)。

    关于c# - 我们可以使用抽象类而不是接口(interface)吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32453805/

    相关文章:

    python - 从静态方法访问静态变量

    java - 为新项目对话框和编辑项目对话框或不同的类设置一个类更好吗?

    java - Eclipse 显示子类(而不是父类)缺少接口(interface)方法

    java - 消除类型转换的需要

    c# - 将 html 添加到 CreateChildControls() 方法

    javascript - ASP.NET MVC 中的 DataTable 应返回哪种类型的数据?

    python - PyQt5 关闭事件方法

    Java 堆栈 push() 与 add()

    c# - Console.WriteLine 不同写法

    c# - 延迟启动 XNA 游戏切换到全屏搞乱介绍屏幕