接口描述属性、方法和事件的特征,但将实现详细信息保留为结构或类。
本演练演示如何声明和实现接口。
注释
本演练不提供有关如何创建用户界面的信息。
注释
计算机可能会在以下说明中显示某些 Visual Studio 用户界面元素的不同名称或位置。 你拥有的 Visual Studio 版本以及所使用的设置决定了这些元素。 有关更多信息,请参阅 自定义 IDE。
定义接口
打开新的 Visual Basic Windows 应用程序项目。
单击“项目”菜单上的“添加模块”,向项目添加新模块。
为新模块
Module1.vb命名,然后单击“ 添加”。 将显示新模块的代码。通过在
TestInterface和Module1语句之间键入Interface TestInterface并按下 Enter,在Module中定义名为End Module的接口。 代码编辑器缩进Interface关键字,并添加一个End Interface语句以形成代码块。通过在
Interface和End Interface语句之间插入以下代码来定义接口的属性、方法和事件:Property Prop1() As Integer Sub Method1(ByVal X As Integer) Event Event1()
执行
你可能会注意到,用于声明接口成员的语法不同于用于声明类成员的语法。 这种差异反映了接口不能包含实现代码的事实。
实现接口
在
ImplementationClass语句之后,但在Module1语句之前,将以下语句添加到End Interface中以添加一个名为End Module的类,然后按下 ENTER 键。Class ImplementationClass如果在集成开发环境中工作, 则代码编辑器 在按 Enter 时提供匹配
End Class语句。将以下
Implements语句添加到ImplementationClass其中,该语句将类实现的接口命名为:Implements TestInterface当与类或结构顶部的其他项分开列出时,
Implements该语句指示类或结构实现接口。如果在集成开发环境中工作, 则代码编辑器 在按 Enter 时实现所需的
TestInterface类成员,你可以跳过下一步。如果不在集成开发环境中工作,则必须实现接口
MyInterface的所有成员。 添加以下代码以实现ImplementationClassEvent1,Method1以及Prop1:Event Event1() Implements TestInterface.Event1 Public Sub Method1(ByVal X As Integer) Implements TestInterface.Method1 End Sub Public Property Prop1() As Integer Implements TestInterface.Prop1 Get End Get Set(ByVal value As Integer) End Set End Property该
Implements语句命名要实现的接口和接口成员。通过将专用字段添加到存储属性值的类来完成定义
Prop1:' Holds the value of the property. Private pval As Integer从属性 get 访问器返回
pval的值。Return pval在属性 set 访问器中设置
pval的值。pval = value通过添加以下代码来完成定义
Method1。MsgBox("The X parameter for Method1 is " & X) RaiseEvent Event1()
测试接口的实现
在 解决方案资源管理器中右键单击项目的启动窗体,然后单击“ 查看代码”。 编辑器将显示启动窗体的类。 默认情况下,启动窗体被称为
Form1。将以下
testInstance字段添加到Form1类:Dim WithEvents testInstance As TestInterface通过将
testInstance声明为WithEvents,Form1类可以处理它的事件。将以下事件处理程序添加到
Form1类以处理由以下项testInstance引发的事件:Sub EventHandler() Handles testInstance.Event1 MsgBox("The event handler caught the event.") End Sub在
Test类中添加一个名为Form1的子例程,以测试实现类。Sub Test() ' Create an instance of the class. Dim T As New ImplementationClass ' Assign the class instance to the interface. ' Calls to the interface members are ' executed through the class instance. testInstance = T ' Set a property. testInstance.Prop1 = 9 ' Read the property. MsgBox("Prop1 was set to " & testInstance.Prop1) ' Test the method and raise an event. testInstance.Method1(5) End Sub该过程
Test创建实现的类MyInterface的实例,将该实例testInstance分配给字段,设置属性,并通过接口运行方法。添加代码以从启动窗体的
Test过程调用Form1 Load过程:Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Test() ' Test the class. End Sub按 F5 运行
Test过程。 将显示消息“Prop1 设置为 9”。 单击“确定”后,将显示消息“Method1 的 X 参数为 5”。 单击“确定”,信息显示为“事件处理程序捕获了事件”。