主题: 共享成员(Shared Member)
?????? 内容 ??????
v 1. 共享资料成员
v 2. 共享程序成员
您已经习惯像 New Employee("Tom", 25)这样的指令了,看到这个指令可以想向它是:Employee.New("Tom", 25),于是不难想象到,原来类别也是对象!这个类别对象(Class Object)接到New()讯息时,就去诞生一个对象,原来类别对象就是妈妈对象(Meta Object)!妈妈是小孩共有的,妈妈的资料值是小孩共享的,妈妈的程序是小孩共享的。本文就介绍这种共享的资料成员和程序成员。
1. 共享资料成员
对象拥有自己的空间﹐也拥有自己的资料﹔对象之间的沟通(交换资料)方法是个重要问题。如果只想传递某项资料时﹐该如何呢﹖
图1、 对象间之沟通
有数种可行方法﹐请看个例子﹕
'ex01.bas
Imports System.ComponentModel
Imports System.Drawing
Imports System.WinForms
'----------------------------------------------------
Class Employee
Private emp_name As String
Public salary As Double
Public Overloads Sub New(ByVal na As String)
emp_name = na
End Sub
Public Overloads Sub New(ByVal na As String, ByVal s As Double)
emp_name = na
salary = s
End Sub
Public Sub Display()
MessageBox.Show("Name: " + emp_name + " Salary: " + str(salary))
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 e1 As New Employee("Tom")
Dim e2 As New Employee("Lily", 20000)
e1.salary = e2.salary + 5000
e1.Display()
e2.Display()
End Sub
End Class
此程序输出如下﹕
Name:Tom Salary:25000
Name:Lily Salary:20000
这宣告salary为public变量﹐让main()能直接使用salary变量。指令:
e1.salary = e2.salary + 5000
把对象e2之salary值加上5000﹐然后存入e1之salary变量中。此程序﹐重复定义了建构者程序── New()﹐宣告对象e1及e2时﹐就有两种选择﹕只输入姓名﹐或同时输入姓名及薪资额。请注意一项缺点﹕把salary宣告为Public变量﹐让Form1_Click()可使用salary变量名称﹐直接把资料存入对象中。若其它程序也依样画葫芦﹐任意把值存入salary中﹐那么salary值可能无意中遭破坏了。
如果salary资料并非机密﹐尚无所谓。如果salary含有极重要资料﹐就得谨慎小心了。就像一颗炸弹(Employee类别)内的炸药(salary资料)可能无意中因外面因素(温度升高等)而引起变化导致爆炸﹐就危险了。
图2、类别之保护功能
因之﹐为让对象之间互相传递资料而把资料成员宣告为Public变量并不甚妥当。希望能像炸弹一样﹐只能经由信管(程序成员)使内部的炸药(salary)起化学作用。于是﹐宣告salary为Private变量﹐把它封藏在Employee的保护之中才安全。类别(及对象)之用途和手表、灯泡、蜗牛的外壳是一样的──保护内部之资料﹐只限特定之管道才能存取资料。然而一旦把salary藏入Employee壳中﹐上述程序就出问题了﹐如下﹕
'ex02.bas
'Some Error Here!
Imports System.ComponentModel
Imports System.Drawing
Imports System.WinForms
'----------------------------------------------------
Class Employee
Private emp_name As String
Private salary As Double
Public Overloads Sub New(ByVal na As String)
emp_name = na
End Sub
Public Overloads Sub New(ByVal na As String, ByVal s As Double)
emp_name = na
salary = s
End Sub
Public Sub Display()
MessageBox.Show("Name: " + emp_name + " Salary: " + str(salary))
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 Initiali