c# - 实现一个接口,该接口继承自两个具有相同方法的接口
问题描述
我有很多接口重叠计算方法的项目:
public interface Interface1
{
public double CalcStuff( int x );
}
public interface Interface2
{
public double CalcStuff( int x );
}
public interface InterfaceJoined : Interface1, Interface2
{
}
public class ClassJoined : InterfaceJoined
{
public double CalcStuff( int x ) { return x*x; }
}
我希望实现类可以分配为所有三个接口Interface1, Interface2, InterfaceJoined
。
Interface1 calculator1 = new ClassJoined( );
Interface2 calculator2 = new ClassJoined( );
InterfaceJoined calculatorJoined = new ClassJoined( );
double result1 = calculator1.CalcStuff( 20 ); // works
double result2 = calculator2.CalcStuff( 20 ); // works
double resultJoined = calculatorJoined.CalcStuff( 20 ); // "the call is ambiguous between the following methods or properties"
我希望接口具有相同的实现。这里无需区分。我怎样才能做到这一点?这整个想法是糟糕的设计吗?
谢谢和问候。
解决方案
我唯一能想到的是将接口的显式默认方法实现与通过关键字隐藏Interface1.CalcStuff
and方法相结合:Interface2.CalcStuff
new
public interface InterfaceJoined : Interface1, Interface2
{
double Interface1.CalcStuff(int x) => CalcStuff(x);
double Interface2.CalcStuff(int x) => CalcStuff(x);
new double CalcStuff(int x);
}
推荐阅读
- http - 基于 HTTP 请求源的路由
- keras - 如何禁用预训练自编码器潜在空间中的神经元?
- boost - 如何使用 boost::property_tree::write_xml 设置目标 XML 文档类型?
- javascript - 如何在 ChartJS Pie 中添加 url?
- c++ - Float* 数据成员没有给出预期的输出
- visual-studio-code - git diff 如何在 vscode 上工作(特别是工作更改)
- c - 如何像在 C++ 中一样比较 C 中的命令行参数
- java - SpringMVC单元测试-控制器中未调用服务方法
- node.js - 我的 fetch POST 返回代码为 200,但我的数据未发布在我的 bdd 上
- deployment - 使用 GIT 集成进行发布时,从 Azure 数据工厂中删除标记