VB.Net中文教程(6) 母子对象关系
点击次数:51 次 发布日期:2008-11-06 08:07:28 作者:源代码网
|
源代码网推荐 ---- 母子对象关系 源代码网推荐 源代码网推荐 大家已经熟悉父子类别关系﹐也就是「继承」关系了。于此说明另一种常见关系── 母子对象。一般称之为「组合/部分」关系。日常生活中﹐处处可见到这种母子对象。例如﹐客厅内有沙发、桌子、椅子等等。客厅是母对象﹐沙发、桌子、椅子是子对象。再如计算机屏幕上的窗口内有按钮、选择表、对话盒等等。窗口是母对象﹐按钮、选择表是子对象。于此将说明如何建立母子对象关系。有了关系﹐母子就能互相沟通了。母子对象之间﹐如何沟通呢﹖也就是说﹐母对象如何呼叫子对象的程序呢﹖反过来﹐子对象如何呼叫母对象的程序呢﹖欲呼叫对方的程序﹐必先与对方建立关系才行。因之﹐如何建立母子对象关系﹐是顶重要之课题﹗ 源代码网推荐 请先看个例子﹐有两个类别──Room和Desk。若Room代表房间﹐Desk代表房间内的桌子﹐则它们会诞生母子对象﹕ 源代码网推荐 源代码网推荐 源代码网推荐 源代码网推荐通常﹐您会依房间的大小来决定桌子的大小。因之﹐Desk对象应跟Room对象沟通﹐取得房间的大小﹐才决定自己的大小。若有个Room之参考﹐则Desk对象就能跟Room对象沟通了。于是﹐可设计下述VB程序: 源代码网推荐 源代码网推荐"ex01.bas 源代码网推荐Imports System.ComponentModel 源代码网推荐Imports System.Drawing 源代码网推荐Imports System.WinForms 源代码网推荐"---------------------------------------------------- 源代码网推荐Class Room 源代码网推荐 Protected rSize As Double 源代码网推荐 Shared motherObject As Room 源代码网推荐 源代码网推荐 Public Sub New() 源代码网推荐 motherObject = Me 源代码网推荐 End Sub 源代码网推荐 Shared Function GetMother() As Room 源代码网推荐 GetMother = motherObject 源代码网推荐 End Function 源代码网推荐 Public Function GetSize() As Double 源代码网推荐 GetSize = rSize 源代码网推荐 End Function 源代码网推荐End Class 源代码网推荐 源代码网推荐Class Desk 源代码网推荐 Protected dSize As Double 源代码网推荐 Public Sub New() 源代码网推荐 dSize = Room.GetMother().GetSize() * 0.18 源代码网推荐 End Sub 源代码网推荐 Public Function GetSize() As Double 源代码网推荐 GetSize = dSize 源代码网推荐 End Function 源代码网推荐End Class 源代码网推荐"---------------------------------------------------- 源代码网推荐Class MyRoom 源代码网推荐 Inherits Room 源代码网推荐 Private rd As Desk 源代码网推荐 源代码网推荐 Public Sub New() 源代码网推荐 rSize = 100 源代码网推荐 rd = New Desk() 源代码网推荐 End Sub 源代码网推荐 Public Sub Show() 源代码网推荐 MessageBox.Show("Room Size: " str(rSize)) 源代码网推荐 MessageBox.Show("Desk Size: " str(rd.GetSize())) 源代码网推荐 End Sub 源代码网推荐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) 源代码网推荐 源代码网供稿. |
