首页 > 解决方案 > 2 个类实现相同的接口,但一个方法在两个类之间具有相同的实现,导致重复代码

问题描述

考虑以下场景:

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 是一个现有的类,Test1 和 Test2 是 TestParent 的子类并实现 ITestInterface。

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

标签: c#.netinterfacearchitecture

解决方案


您需要添加一个扩展 TestParent 并实现 TestMethod2() 的中间类 (TestParentExtension)。然后,您可以为 Test1 和 Test2 而不是 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");
  }
}

推荐阅读