c# - 接口(interface)、抽象或只是虚拟方法?

标签 c# oop interface abstract-class virtual-functions

我有一堆系统,我们称它们为 A、B、C、D、E、F、G、H、I、J

它们都有相似的方法和属性。有些包含完全相同的方法和属性,有些可能略有不同,有些可能差异很大。现在,每个系统都有很多重复的代码。例如,我有一个为每个系统定义的名为 GetPropertyInformation() 的方法。我试图弄清楚哪种方法是减少重复代码的最佳方法,或者下面的方法之一可能不是可行的方法:

界面

public Interface ISystem
{
    public void GetPropertyInformation();
    //Other methods to implement
}

public class A : ISystem
{
    public void GetPropertyInformation()
    {
       //Code here
    }
}

摘要

public abstract class System
{
    public virtual void GetPropertyInformation()
    {
        //Standard Code here
    }
}

public class B : System
{
   public override void GetPropertyInformation()
   {
      //B specific code here
    }
}

超基类中的虚方法

public class System
{
   public virtual void GetPropertyInformation()
    {
     //System Code
    }
}

public class C : System
{
  public override void GetPropertyInformation()
  {
      //C Code
  }
}

有一个问题,虽然它可能很愚蠢,但我们假设我采用了抽象方法并且我想覆盖 GetPropertyInformation,但我需要向它传递一个额外的参数,这可能吗?我必须在抽象类中创建另一个方法吗?例如,GetPropertyInformation(x)

最佳答案

您的抽象方法和“ super 基类”方法并没有太大区别。您应该始终使基类抽象,并且您可以提供默认实现(虚方法)或不提供(抽象方法)。决定因素是你是否想要拥有基类的实例,我认为不是。

所以它介于基类和接口(interface)之间。如果您的 A、B C 类之间存在强耦合,那么您可以使用基类和可能的通用实现。

如果 A、B、C 类自然不属于一个“家族”,则使用接口(interface)。

System 可不是什么好名字。

并且您不能在覆盖时更改参数列表。也许默认参数可以提供帮助,否则您只需要 2 个 GetPropertyInformation() 重载。

关于c# - 接口(interface)、抽象或只是虚拟方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7589147/

相关文章:

java - 六角网格上的元胞自动机

java - Universal-Image-Loader 中多重继承的一个不确定性

c# - 为什么我不能引用具有部分父实体复合键的子实体

python - python中如何通过调用__init__方法中的方法来引入对象的属性?

c# - 从运行时创建的对象订阅事件

php - Symfony 2 表单错误

c# - C# 中的 "Abstract"接口(interface)

java - 如何通过示例使用 Java 创建我自己的自定义界面

c# - .csproj 文件无法正确导入其他项目

c# - 具有 IoT 中心的 Azure Functions 无法检索分区