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

时间:2010-05-14 06:11:48

标签: c# oop interface

说,我有三个接口:

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

从这三个接口继承的类:

class ABC: I1,I2, I3
{
      // method definitions
}

问题:

  • 如果我这样实现:

    ABC类:I1,I2,I3    {

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

    }

它编译得很好,也运行得很好! 这是否意味着这个单一方法实现足以继承所有三个接口?

  • 如何实现所有三个界面的方法并 CALL THEM ? 像这样:

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

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

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:2)

你可以打电话给它。您只需使用具有接口类型的引用:

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

如果你有:

ABC abc = new ABC();

你可以这样做:

I1 abcI1 = abc;
abcI1.XYZ();

或:

((I1)abc).XYZ();

答案 2 :(得分:2)

在类中实现期间不指定修饰符o / w您将得到编译错误,还要指定接口名称以避免歧义。您可以尝试代码:

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();
}

}