VB.NET之旅(九)—接口继承2012-09-03 韩睿 大李拍了拍我的肩膀说:“你真有想象力,不过的确,有很多文献把这 种用Implements来实现接口的方法就称为接口继承。其实,接口自己也是可以进 行继承的,在VB.NET中把接口间的继承形式称为接口继承。”我不 禁跟着笑了起来:“接口继承要成为继承,当然要用Inherits,对吧? ”大李点点头说:“既然你都清楚了,那你来模拟一个下拉框 Combobox的接口吧。”“Combobox?”我不禁一愣,不 过一会就想明白了,“是不是要让它符合有文本框供文字输入与下拉列表供 选择列表项的组合形式这样的外观?”大李跟着提醒了我一句: “接口与VB.NET中的类继承还是有不同的,它可以支持从多个接口进行多重 继承,VB.NET中的类只支持单一基类的继承。”见大李没什么别的 意见,我就开始写起代码来:
Interface IControl Sub Paint() End Interface Interface ITextBox Inherits IControl ‘在文本框设置文本 Sub SetText(ByVal text As String) End Interface Interface IListBox Inherits IControl ‘在下拉列表设置列表项 Sub SetItems(ByVal items() As String) End Interface Interface IComboBox Inherits ITextBox, IListBox End Interface Class CHenry Implements IComboBox Sub SetText(ByVal text As String) Implements ITextBox.SetText "实现代码 End Sub Sub SetItems(ByVal items() As String) Implements IListBox.SetItems "实现代码 End Sub ……
写到这,发现CHenry类中的Implements IcomboBox的ICombobox下面还有一条波浪线,说明接口并没有实现完毕,可是我 已经把IComboBox继承的两个基接口中的方法都已经实现了呀。把鼠标靠近波浪线 一看,系统提示“必须为接口IControl实现sub Paint()”,于是我就 继续写:
Sub Paint() Implements IControl.Paint "实现代码 End Sub End Class
我转回头问大李:“接口的实现类中是不是要把 接口的所有基接口都要实现一遍呀?”大李点点头说:“如果 象这个演练中的情况,当然是要把基接口中没有实现的方法进行实现。但也要注 意,实现接口的类或结构会隐式地实现该接口的所有基接口。如果一个接口在基 接口的可传递闭包中多次出现,它的成员只参与一次构成派生接口。实现派生接 口的类型只需实现一次多次定义的基接口方法。所以你也可以用Sub Paint() Implements ITextbox.Paint或是Sub Paint() Implements IListBox.Paint来代 替,但只能用这三个定义中的一个。你再来看这段代码。”大李开始修改起 刚写好的代码来:
Interface IControl Sub Paint() End Interface Interface ITextBox Inherits IControl ‘在文本框设置文本 Sub SetText(ByVal text As String) Shadows Sub Paint() End Interface Interface IListBox Inherits IControl ‘在下拉列表设置列表项 Sub SetItems(ByVal items() As String) End Interface Interface IComboBox Inherits ITextBox, IListBox End Interface Sub test(ByVal x As IComboBox) x.Paint() End Sub