如果此程序改写为﹕
'ex09.bas 'Some Error Here! Imports System.ComponentModel Imports System.Drawing Imports System.WinForms '---------------------------------------------- Class Tree Private varity As String Private age As Integer Private height As Single Private Sub input(ByVal hei As Single) height = hei 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) Dim a As New Tree() a.input(2.1) MessageBox("OK") End Sub End Class
这程序有问题﹐因为 input()是Tree类别之Private程序成员而非Public程序成员﹐所以不能使用如下格式──
所以此程序错了。 请再看个例子吧﹗
'ex10.bas Imports System.ComponentModel Imports System.Drawing Imports System.WinForms '------------------------------------------- Class Tree Private varity As String Private height As Single Public age As Integer Public Sub ShowAge() MessageBox.Show("Age = " + str(Age)) 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) Dim a As New Tree() a.age = 8 a.age = a.age + 2 a.ShowAge() End Sub End Class
Tree类别包含 2个Private成员── variety及height﹐且有 2个Public成员── age及 ShowAge()。由于age是Public资料成员﹐所以Fom1_Click()可使用格式──
来存取Tree内之age变量。指令── a.age = 8把8存入对象 a内之age 变量。指令──a.age = a.age + 2使对象a之age变量值加上2﹐成为10。由于ShowAge()程序是Public程序成员﹐也可使用格式──
来呼叫 ShowAge()程序。 由于类别(即对象)之目的是保护资料﹐并且提供程序成员来与外界沟通(接受、处理、并反应讯息)。通常﹐资料成员皆宣告为Private﹐而程序成员皆宣告为Public。亦即尽量少用格式──
而尽量多用格式──
例如﹕
'ex11.bas Imports System.ComponentModel Imports System.Drawing Imports System.WinForms '-------------------------------------------------------------------- Class Tree Private varity As String Private age As Integer Private height As Single Public Sub input(ByVal v As String, ByVal a As Integer, ByVal hei As Single) varity = v age = a height = hei End Sub Public Sub Show() MessageBox.Show(varity + ", " + str(age) + ", " + str(height)) End Sub End Class '--------------------------------------------------------------------- Public Class Form1 Inherits System.WinForms.Form
(编辑:aniston)
|