首页 > 解决方案 > 实现一个接口,该接口继承自两个具有相同方法的接口

问题描述

我有很多接口重叠计算方法的项目:

    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"

我希望接口具有相同的实现。这里无需区分。我怎样才能做到这一点?这整个想法是糟糕的设计吗?

谢谢和问候。

标签: c#interfacemultiple-inheritance

解决方案


我唯一能想到的是将接口的显式默认方法实现与通过关键字隐藏Interface1.CalcStuffand方法相结合:Interface2.CalcStuffnew

public interface InterfaceJoined : Interface1, Interface2
{
    double Interface1.CalcStuff(int x) => CalcStuff(x);
    double Interface2.CalcStuff(int x) => CalcStuff(x);
    new double CalcStuff(int x);
}

推荐阅读