如果一个类实现了两个或两个以上名字、类型和参数类型都相同的接口,那么类中的一个成员就可能实现所有这些接口成员:
interface IControl
{
void Paint( ) ;
}
interface IForm
{
void Paint( ) ;
}
class Page: IControl, IForm
{
public void Paint( ) {…}
}
这里,接口IControl和IForm的方法Paint都映射到了类Page中的Paint方法。当然也可以分别用显式的接口成员分别实现这两个方法:
interface IControl
{
void Paint( ) ;
}
interface IForm
{
void Paint( ) ;
}
class Page: IControl, IForm
{
public void IControl.Paint( )
{
//具体的接口实现代码
}
public void IForm.Paint( )
{
//具体的接口实现代码
}
}
--------------------------------------------------------------------------
另一种情况是,如果一个类实现了多个接口,这些接口又拥有同一个父接口,这个父接口只允许被实现一次。
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) {…}
}
实际上,对接口ITextBox 和IListBox 的实现,分享了对接口IControl 的实现
interface IControl
{
void Paint( ) ;
}
interface IForm
{
void Paint( ) ;
}
class Page: IControl, IForm
{
public void Paint( ) {…}
}
这里,接口IControl和IForm的方法Paint都映射到了类Page中的Paint方法。当然也可以分别用显式的接口成员分别实现这两个方法:
interface IControl
{
void Paint( ) ;
}
interface IForm
{
void Paint( ) ;
}
class Page: IControl, IForm
{
public void IControl.Paint( )
{
//具体的接口实现代码
}
public void IForm.Paint( )
{
//具体的接口实现代码
}
}
--------------------------------------------------------------------------
另一种情况是,如果一个类实现了多个接口,这些接口又拥有同一个父接口,这个父接口只允许被实现一次。
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) {…}
}
实际上,对接口ITextBox 和IListBox 的实现,分享了对接口IControl 的实现
接口:接口的定义是为了类和类之间进行交互。
楼主可能的疑惑:那么类与类之间直接交互就好了,为什么还要使用接口呢?(引用)这主要是因为:接口是类之间交互内容的一个抽象,把类之间需要交互的内容抽象出来定义成接口,可以更好的控制类之间的逻辑交互。可见接口内容的抽象好坏关系到整个程序的逻辑质量;另外可以在任何时候通过开发附加接口和实现来添加新的功能;
关于接口一个很重要的概念:接口只包含成员定义,不包含成员的实现,成员的实现需要在继承的类或者结构中实现。
接口的成员包括:方法,特性,索引器,事件
更多可以使用google查询。