interface IControl {
void Paint( ) ;
}
interface IForm {
void Paint( ) ;
}
class Page: IControl, IForm {
public void IControl.Paint( ) {
//具体的接口实现代码
}
public void IForm.Paint( ) {
//具体的接口实现代码 http://www.easck.com/
}
}
上面的两种写法都是正确的。但是如果接口成员在继承中覆盖了父接口的成员,那么对该接口成员的实现就可能必须映射到显式接口成员执行体。看下面的例子:
interface IBase {
int P { get; }
}
interface IDerived: IBase {
new int P( ) ;
}
接口IDerived从接口IBase中继承,这时接口IDerived 的成员方法覆盖了父接口的成员方法。因为这时存在着同名的两个接口成员,那么对这两个接口成员的实现如果不采用显式接口成员执行体,编译器将无法分辨接口映射。所以,如果某个类要实现接口IDerived,在类中必须至少定义一个显式接口成员执行体。采用下面这些写法都是合理的:
//一:对两个接口成员都采用显式接口成员执行体来实现
class C: IDerived {
int IBase.P
get
{ //具体的接口实现代码 }
int IDerived.P( ){
//具体的接口实现代码 }
}
//二:对Ibase 的接口成员采用显式接口成员执行体来实现
class C: IDerived {
int IBase.P
get {//具体的接口实现代码}
public int P( ){
//具体的接口实现代码 }
}
//三:对IDerived 的接口成员采用显式接口成员执行体来实现
class C: IDerived{
public int P
get {//具体的接口实现代码}
int IDerived.P( ){
//具体的接口实现代码}
}
另一种情况是,如果一个类实现了多个接口,这些接口又拥有同一个父接口,这个父接口只允许被实现一次。
using System ;
interface IControl {
void Paint( ) ;
interface ITextBox: IControl {
void SetText(string text) ;
}
interface IListBox: IControl {
void SetItems(string[] items) ;
}
class ComboBox: IControl, ITextBox, IListBox {
void IControl.Paint( ) {…}
void ITextBox.SetText(string text) {…}
void IListBox.SetItems(string[] items) {…}
}
上面的例子中,类ComboBox实现了三个接口:IControl,ITextBox和IListBox。如果认为ComboBox不仅实现了IControl接口,而且在实现ITextBox和IListBox的同时,又分别实现了它们的父接口IControl。实际上,对接口ITextBox 和IListBox 的实现,分享了对接口IControl 的实现。










