2 类 实现相同的接口,但一个方法在 类 中具有相同的实现,导致重复代码

2 classes implement the same interface, but a method has the same implementation across both the classes causing duplicate code

考虑以下场景:

public interface ITestInterface
{
   void TestMethod1();
   void TestMethod2();
}


public class TestParent
{
    void SomeMethod()
    {
        Console.Writeln("Method of test parent");
    }
}

public class Test1: TestParent, ITestInterface
{
  void TestMethod1()
  {
     Console.WriteLine("Implementation 1 of TestMethod1");
  }

  void TestMethod2()
  {
     Console.log("Same implementation");
  }
}

public class Test2: TestParent, ITestInterface
{
  void TestMethod1()
  {
     Console.WriteLine("Implementation 2 of TestMethod1");
  }

  void TestMethod2()
  {
     Console.log("Same implementation");
  }
}

TestParent 是现有的 class,Test1 和 Test2 是 TestParent 的子 classes 并实现 ITestInterface。

在我上面的示例中,class 都具有相同的 TestMethod2() 实现。 我只是想知道如何避免重复代码? 我计划添加更多 classes,它们都具有相同的 TestMethod2 实现。

你为什么不使用(抽象的)基础 class?

public abstract class TestBase: TestParent, ITestInterface
{
    void SomeMethod()
    {
        Console.Writeln("Method of test parent");
    }

    #region ITestInterface

    public void TestMethod1()
    {
        Console.WriteLine("Implementation 1 of TestMethod1");
    }

    public void TestMethod2()
    {
        Console.log("Same implementation");
    }

    #endregion
}

public class Test1 : TestBase
{
}

public class Test2 : TestBase
{
}

您需要添加一个扩展 TestParent 并实现 TestMethod2() 的中间体 class(TestParentExtension)。然后,您可以为 Test1 和 Test2 扩展这个中间 class 而不是 TestParent。

给你。我为您清理了一些语法。

public interface ITestInterface {
  void TestMethod1();
  void TestMethod2();
}

public class TestParent {
  public void SomeMethod() {
    Console.WriteLine("Method of test parent");
  }
}

public class IntermediateParent: TestParent {
  public void TestMethod2() {
    Console.WriteLine("Same implementation");
  }
}

public class Test1: IntermediateParent, ITestInterface {
  public void TestMethod1() {
    Console.WriteLine("Implementation 1 of TestMethod1");
  }

}

public class Test2: IntermediateParent, ITestInterface {
  public void TestMethod1() {
    Console.WriteLine("Implementation 2 of TestMethod1");
  }
}