【问题标题】:2 classes implement the same interface, but a method has the same implementation across both the classes causing duplicate code2 个类实现相同的接口,但一个方法在两个类之间具有相同的实现,导致重复代码
【发布时间】:2021-08-05 20:41:16
【问题描述】:

考虑以下场景:

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# .net interface architecture


【解决方案1】:

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

【讨论】:

  • 谢谢,我会接受这个作为答案。但是,当蒂姆回答时,我错过了一些上下文,但他的意思是一样的。
【解决方案2】:

为什么不使用(抽象)基类?

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 是一个现有的类,我需要扩展实现 ITestInterface 的类。
  • @kaikadi-bella:由于您提供了伪类,因此很难建议您如何重构代码。比如不能让TestParent实现接口?或者另一种方式,让TestBase 继承自TestParent(编辑我的答案)。
  • TestParent 无法实现该接口,因为 TestParent 的其他派生类实现了其他接口。添加从 TestParent 继承的 TestBase 就可以了。谢谢!
猜你喜欢
  • 2014-03-05
  • 2014-10-25
  • 2015-09-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多