C# 接口、枚举与泛型深入解析
1. 接口实现
在 C# 中,当多个接口存在冲突的方法签名时,我们可以采用显式实现接口方法的方式来解决。例如:
interface I1 { void Foo(); }
interface I2 { int Foo(); }
public class Widget : I1, I2
{
public void Foo() // Implicit implementation
{
Console.Write ("Widget's implementation of I1.Foo");
}
int I2.Foo() // Explicit implementation of I2.Foo
{
Console.Write ("Widget's implementation of I2.Foo");
return 42;
}
}
这里, I1 和 I2 都有 Foo 方法,但签名不同。 Widget 类显式实现了 I2 的 Foo 方法,使得这两个方法能在同一个类中共存。调用显式实现的成员时,需要将对象转换为对应的接口类型:
Widget w = new Widget();
w.Foo(); // Widget's implementation
超级会员免费看
订阅专栏 解锁全文
19

被折叠的 条评论
为什么被折叠?



