当前位置:编程学习 > VB >>

VB.Net中文教程(4) 母子对象关系(5)

 

 

Function yourID() As String

End Interface

 

Class Room

   Private mother As IMyRoom

  

   Public Sub New(ByVal mo As IMyRoom)

       mother = mo

   End Sub

   Public Function GetID() As String

       GetID = "RoomID: " + mother.yourID()

   End Function

End Class

 

Class MyRoom

   Implements IMyRoom

   Private base As Room

  

   Public Sub New()

       base = New Room(Me)

   End Sub

   Public Function yourID() As String Implements IMyRoom.yourID

       yourID = "VIP888"

   End Function

   Public Function GetID() As String

       GetID = base.GetID()

   End Function

End Class

----------------------------------------------------

Public Class Form1

   Inherits System.WinForms.Form

  

   Public Sub New()

       MyBase.New()

       Form1 = Me

       This call is required by the Win Form Designer.

       InitializeComponent()

       TODO: Add any initialization after the InitializeComponent() call

   End Sub

   Form overrides dispose to clean up the component list.

   Public Overrides Sub Dispose()

       MyBase.Dispose()

       components.Dispose()

   End Sub

#Region " Windows Form Designer generated code "

   .......

#End Region

   Protected Sub Form1_Click(ByVal sender As Object, ByVal e As System.EventArgs)

       Dim r As New MyRoom()

       MessageBox.Show(r.GetID())

   End Sub

End Class

 

此程序输出﹕

                RoomID: VIP888

 

   一般使用委托(Delegation)来代替继承时,常用的手法。然而上述ex08.bas程序的MyRoom类别里面用到了Room名称,如果您不希望如此,可定义一个IRoom接口,供MyRoom类别使用,如下程序:

 

ex09.bas

Imports System.ComponentModel

Imports System.Drawing

Imports System.WinForms

----------------------------------------------------

Interface IMyRoom

  

补充:软件开发 , Vb ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,