c# - C#中的多接口(interface)继承

标签 c# oop interface

我有两个使用相同方法的接口(interface)

   interface FirstInterface
   {
     int add(int x, int y);
   }

   interface SecondInterface
   {
      int add(int x, int y);
   }

   class TestInterface:FirstInterface,SecondInterface
   {
     public TestInterface() {}

     public int add(int x, int y)
     {
        return x + y;
     }
   }

在我的主课上

    static void Main(string[] args)
    {
        TestInterface t = new TestInterface();
        int result = t.add(3, 4);

    }

编译器没有给出任何错误并显示结果..

对不对??我们不应该使用 FirstInterface.add 吗??

这是否意味着接口(interface)在编译时解析 ??

最佳答案

这是Explicit or Implicit的主题接口(interface)的实现。

如果你实现了Interface AInterface B,并且它们都有一个名为Foo的成员,这是一个方法,那么如果你在一个类中实现这些接口(interface),您唯一的方法 Foo 将对它们都有效。这是设计使然,坦率地说,我认为对此没有其他解决办法。

要分别实现它们,您必须使用Explicit Interface Implementation,也就是说,您在Foo 方法的名称前加上接口(interface)名称和一个点,例如 InterfaceA.FooInterfaceB.Foo

引自C# specification :

20.3 Fully qualified interface member names

An interface member is sometimes referred to by a qualified interface member name. A qualified interface member name consists of a name identifying the interface in which the member is declared, followed by a dot, followed by the name of the member.

关于c# - C#中的多接口(interface)继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19946103/

相关文章:

c# - 管理代码 Assets

c# - 使用多字段过滤概念化高级 linq 查询

c++ - 我在这里使用全局状态吗,有没有更好的方法来做到这一点?

python - 类和函数范围

c# - 显式接口(interface)实现限制

c# - 如何使用 C# 代码访问共享网络驱动器文件

c# - 在 C# 中多线程处理多个文件的最佳方法是什么?

java - 无法解析私有(private)方法内的变量

python - DBus 接口(interface)属性

json - 使用 2 种嵌套类型解析 JSON