它视inquireHeight()为一独立之程序﹐与Tree类别内之inquireHeight()无关﹔于是计算机去找此inquireHeight()之定义﹐但找不着﹔所以程序错了。因之﹐您要掌握个原则── 程序成员之唯一任务是支持对象之行为﹐必须与对象配合使用。 2. 「封装性」概念
对象把资料及程序组织并「封装」(Encapsulate) 起来﹐只透过特定的方式才能使用类别之资料成员和程序成员。对象如同手提袋﹐只从固定的开口才能存取东西﹐否则您一定不敢把钱放在手提袋中。对象像一座「防火墙」保护类别中的资料﹐使其不受外界之影响。想一想我国的万里长城可保护关内的人民﹐避免受胡人侵犯﹐但长城并非完全封闭﹐而有山海关、玉门关等出入口。对象和万里长城之功能是一致的﹐它保护其资料成员﹐但也有正常的资料存取管道﹕以程序成员来存取资料成员。请看个程序﹕
'ex05.bas Imports System.ComponentModel Imports System.Drawing Imports System.WinForms '------------------------------------------------------- Class Tree Public varity As String Public age As Integer Public height As Single 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 a As New Tree() a.height = 2.1 Messagebox.Show("height = " + str(a.height) + "公尺") End Sub End Class
此程序输出如下﹕height = 2.1公尺 此程序中﹐Tree类别含有 3个资料成员﹐即对象内含有3个资料值,此类别之程序成员能直接存取之。同时,也允许其它程序来存取资料成员之值﹐其存取格式为﹕
例如﹕ a.height = 2.1
此指令把 2.1存入对象 a之height变量中。于是对象 a之内容为﹕
请看个常见错误如下﹕
'ex06.bas 'Some Error Here! Imports System.ComponentModel Imports System.Drawing Imports System.WinForms '-------------------- ------------------------------------ Class Tree Public varity As String Public age As Integer Public height As Single 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 a As New Tree() height = 2.1 Messagebox.Show("height = " + str(a.height) + "公尺") End Sub End Class
Form1_Click()程序内之指令── height = 2.1,此height变量并未与对象配合使用﹐计算机不认为它是Tree类别之height变量。计算机视其为Form1_Click()之自动变量(Automatic Variable)﹐但却未见到它的宣告﹐因之程序错了﹗这是对象对其资料成员保护最松的情形﹐因为对象所属类别(即Tree)之外的程序(如Form1_Click()程序)尚能存取资料成员的内容。就像一颗炸弹﹐除了引信管外﹐尚有许多管道可使炸弹内之化学药品爆炸﹔您将不敢把炸弹摆在飞机上﹐因何时会爆炸将无法控制。同理﹐Tree类别之资料──height变量﹐连外部的Form1_Click()皆可随意改变它﹔那么有一天height之内容出问题了﹐将难以追查出错之缘故﹐这种程序将让您大伤脑筋﹐因为您已无法掌握状况了。 现在的VB程序中﹐能采取较严密之保护措施﹐使您较能控制类别内资料的变化状况。例如﹐
(编辑:aniston)
|