我有两个使用相同方法的接口(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 A
和Interface B
,并且它们都有一个名为Foo
的成员,这是一个方法,那么如果你在一个类中实现这些接口(interface),您唯一的方法 Foo
将对它们都有效。这是设计使然,坦率地说,我认为对此没有其他解决办法。
要分别实现它们,您必须使用Explicit Interface Implementation
,也就是说,您在Foo
方法的名称前加上接口(interface)名称和一个点,例如 InterfaceA.Foo
和 InterfaceB.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/