c# - 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 实现。
解决方案
您需要添加一个扩展 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");
}
}
推荐阅读
- javascript - 用于图表的 React UseEffect 数据数组
- ios - 来自“[任何]?”的演员表 到不相关的类型“SpotlightView”总是失败
- ios - 如何根据测验结果对单元格进行排序?
- javascript - 反应错误:渲染没有返回任何内容。这通常意味着缺少 return 语句。或者,不渲染任何内容,返回 null
- python - 如何检查机器人连接的语音通道 ID?(discord.py)
- javascript - Django 模板 - 列表未正确呈现
- node-red - 有没有办法选择在 NodeRED 服务器中创建的类别?
- ios - 验证后无法直接登录,但第二次点击成功
- mysql - SQL查询如何添加不存在的列
- datadog - 为 Datadog 浏览器日志添加标签