继承多个具有相同方法签名的接口的类

8

假设我有三个接口:

public interface I1
{
    void XYZ();
}
public interface I2
{
    void XYZ();
}
public interface I3
{
    void XYZ();
}

继承这三个接口之一的类:
class ABC: I1,I2, I3
{
      // method definitions
}

问题:

  • If I implement like this:

    class ABC: I1,I2, I3 {

        public void XYZ()
        {
            MessageBox.Show("WOW");
        }
    

    }

它编译良好,运行也很好!这是否意味着此单个方法实现足以继承所有三个接口?
  • How can I implement the method of all the three interfaces and CALL THEM? Something Like this:

    ABC abc = new ABC();
    abc.XYZ(); // for I1 ?
    abc.XYZ(); // for I2 ?
    abc.XYZ(); // for I3 ?
    

我知道可以使用显式实现来完成,但我无法调用它们。:(

3个回答

8

如果您使用显式实现,则必须将对象强制转换为要调用其方法的接口:

class ABC: I1,I2, I3
{
    void I1.XYZ() { /* .... */ }
    void I2.XYZ() { /* .... */ }
    void I3.XYZ() { /* .... */ }
}

ABC abc = new ABC();
((I1) abc).XYZ(); // calls the I1 version
((I2) abc).XYZ(); // calls the I2 version

有趣的是在C#中可以实现这一点!据我所知,在Java中无法在同一类中分别实现冲突的接口方法。 - Christian Semrau
1
是的,这是可能的,但我通常不建议这样做(会令人困惑)。我认为唯一合理的情况是在实现 ICollection<T> 等操作时,您希望将非泛型的 IEnumerable 实现“隐藏”在正常类定义之外。 - Dean Harding

2
在类的实现中不要指定修饰符,否则会导致编译错误。另外,为避免歧义,请指定接口名称。您可以尝试以下代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleCSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            MyClass mclass = new MyClass();

            IA IAClass = (IA) mclass;
            IB IBClass = (IB)mclass;

            string test1 = IAClass.Foo();
            string test33 = IBClass.Foo();


            int inttest = IAClass.Foo2();
            string test2 = IBClass.Foo2();


            Console.ReadKey();
        }
    }
public class MyClass : IA, IB
{
    static MyClass()
    {
        Console.WriteLine("Public class having static constructor instantiated.");
    }
    string IA.Foo()
    {
        Console.WriteLine("IA interface Foo method implemented.");
        return ""; 
    }
    string IB.Foo()
    {
        Console.WriteLine("IB interface Foo method  having different implementation. ");
        return "";
    }

    int IA.Foo2()
    {
        Console.WriteLine("IA-Foo2 which retruns an integer.");
        return 0;
    }

    string IB.Foo2()
    {
        Console.WriteLine("IA-Foo2 which retruns an string.");
        return "";
    }
}

public interface IA
{
    string Foo(); //same return type
    int Foo2(); //different return tupe
}

public interface IB
{
    string Foo();
    string Foo2();
}

}


2

您可以调用它。您只需使用接口类型的引用:

I1 abc = new ABC();
abc.XYZ();

如果您拥有以下内容:

ABC abc = new ABC();

您可以做:

I1 abcI1 = abc;
abcI1.XYZ();

或者:

((I1)abc).XYZ();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接