继承自具有相同方法签名的多个接口的类 [英] Class inheriting from several Interfaces having same method signature
问题描述
说,我有三个接口:
public interface I1
{
void XYZ();
}
public interface I2
{
void XYZ();
}
public interface I3
{
void XYZ();
}
从这三个接口继承的类:
A class inheriting from these three interfaces:
class ABC: I1,I2, I3
{
// method definitions
}
问题:
-
如果我实现如下:
If I implement like this:
类ABC:I1,I2,I3
{
class ABC: I1,I2, I3 {
public void XYZ()
{
MessageBox.Show("WOW");
}
}
它编译得很好,也运行得很好!
这是否意味着这个单一方法实现足以继承所有三个接口?
It compiles well and runs well too! Does it mean this single method implementation is sufficient for inheriting all the three Interfaces?
-
我如何实现所有三个接口的方法和 CALL THEM ?
像这样:
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 ?
我知道它可以使用显式实现完成但是我无法打电话给他们。 :(
I know it can done using explicit implementation but I'm not able to call them. :(
推荐答案
如果使用显式实现,则必须将对象强制转换为要调用其方法的接口:
If you use explicit implementation, then you have to cast the object to the interface whose method you want to call:
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
这篇关于继承自具有相同方法签名的多个接口的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!