首页 > 编程 > .NET > 正文

VB.Net中文教程(12) 共享成员(Shared Member)

2024-07-10 13:02:42
字体:
来源:转载
供稿:网友
主题: 共享成员(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 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 'error !
e1.display()
e2.display()
end sub
end class

因为salary变成 private变量﹐form1_click()不能使用它﹗


为了将传递之过程纳入类别保护之中﹐有数种方法,例如:

'ex03.bas
imports system.componentmodel
imports system.drawing
imports system.winforms
'----------------------------------------------------------------------
class employee
private shared temp as double
private emp_name as string
private salary as double

shared sub new()
temp = 0
end sub
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 addsalaryto(byval emp as employee , byval money as double)
salary = emp.salary + money
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.addsalaryto(e2, 5000)
e1.display()
e2.display()
end sub
end class

此程序输出如下﹕
name:tom salary:25000
name:lily salary:20000

指令── salary = emp.salary + money 已经在employee类别的保护中,这是不错的做法。
另一种方法是采用共享资料成员,是同一类别里各对象皆共享其值;一般资料成员的值是封装于各对象内,别的对象是拿不到的。共享资料成员的值是在对象之外,但封装在类别内,只要是该类别的对象皆能拿到该值。因为一般资料成员的值封装于对象内,所以又称为对象变量(instance variable);共享资料成员封装于类别,所以又称为类别变量(class variable)。上述程序可改用共享变量如下﹕

'ex04.bas
imports system.componentmodel
imports system.drawing
imports system.winforms
'----------------------------------------------------
class employee
private emp_name as string
private salary as double
private shared temp as double

public overloads sub new(byval na as string)
emp_name = na
end sub
shared sub new()
temp = 0
end sub
public overloads sub new(byval na as string, byval s as double)
emp_name = na
salary = s
end sub
public sub output()
temp = salary
end sub
public sub input()
salary = temp
end sub
public sub add_temp(byval money as double)
temp = temp + money
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)
e2.output()
e2.add_temp(5000)
e1.input()
e1.display()
e2.display()
end sub
end class

此程序输出如下﹕
name:tom salary:25000
name:lily salary:20000


宣告指令── private shared temp as double
说明了﹐temp是共享资料成员。兹归纳,共享资料成员与一般资料成员之区别为:

「共享资料成员是各对象公用的资料﹐
而一般资料成员是对象之私有资料。」

当第1次诞生对象时﹐共享资料成员就由shared sub new()诞生了。当执行到指令──
dim e1 as new employee("tom")

就诞生对象e1。但temp比e1早诞生。接下来﹐执行指令──
employee e2( "lily", 20000 )

它诞生对象e2。此时employee类别之内容为﹕



图3、类别沟通方式──使用共享资料成员

其中﹐e1及e2各含有一份emp_name及salary资料。然而整个employee类别才只有一份temp资料﹐对象共同分享此temp内之资料。employee类别里的任何对象皆可视temp为其资料成员来使用﹐但事实上只有一个temp。由于它属于所有的对象﹐所以各对象皆可经由程序成员存取temp资料。重要的是﹐temp已在employee类别的保护之中﹐藉由它传递资料就无受外界干扰之虞了。
共享资料成员除了供对象之间的沟通之用外﹐还有其重要的用途──记载类别的状况﹐例如记录该类别共诞生了多少对象。请看个例子﹕

'ex05.bas
imports system.componentmodel
imports system.drawing
imports system.winforms
'-----------------------------------------------------------
class employee
private emp_name as string
private salary as double

private shared counter as integer
private shared sum as double

shared sub new()
counter = 0
sum = 0
end sub
public sub new(byval na as string, byval s as double)
emp_name = na
salary = s
counter = counter + 1
sum = sum + salary
end sub
public sub display_avg()
messagebox.show("the number of employee : " + str(counter))
messagebox.show("average salary : " + str(sum / counter))
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", 25000)
dim e2 as new employee("lily", 20000)
e1.display()
e2.display()
e1.display_avg()
end sub
end class

此程序输出﹕
name: tom salary: 25000
name: lily salary: 20000
the number of employee : 2
average salary : 22500

counter 记录类别中含有多少对象。sum 储存各对象的salary值之总和。于此﹐必须给予 counter及 sum初值。共享变量之初值设定格式为──

shared sub new()
共享资料成员1 = 初值
共享资料成员2 = 初值
......
end sub

计算机开始执行,诞生第1个对象时﹐各共享成员就诞生了﹐而且设定了初值。此时employee类别的内容为﹕



对象诞生时﹐会去执行建构者程序──public sub new(...),先把各资料存入对象之私有成员中﹔同时也执行指令──counter = counter + 1﹐使共享变量 counter值加上 1。此外﹐也执行指令──sum = sum + salary ﹐把e1之salary值加到 sum里头。此时共享变量的内容为﹕



counter 值为 1﹐表示employee内已诞生一个对象。接着﹐诞生个体e2﹐计算机又执行建构者程序──public sub new(...)。它把资料存入对象e2中﹐使 counter加上 1﹐也把e2之salary值加到 sum中。此时﹐共享变量之内容为﹕



注意﹐e1含有 4个资料成员──emp_name、salary、counter 及sum ﹔其值分别为 "tom"、 25000、 2及 45000。同时e2含有4 个资料成员──emp_name、salary、counter 及 sum﹔其值分别为"lily"、20000 、2 及 45000。只是e1之 counter值等于e2之 counter值﹐同时e1之sum 值等于e2之 sum值。




2. 共享程序成员
刚才介绍过共享资料成员(shared data member)之观念。共享资料成员是各对象的公用数据成员﹐但并不属于任何对象﹐而是属于类别的。除了资料成员之外,也有共享程序成员,它是属于类别的﹐而并不属于任何对象﹐其不是用来存取某对象内的值﹐而只储存取共享资料成员之值。任何一般程序成员皆可呼叫共享程序成员来存取共享成员之值。例如﹕

'ex06.bas
imports system.componentmodel
imports system.drawing
imports system.winforms
'----------------------------------------------------------------------
class employee
private emp_name as string
private salary as double

private shared counter as integer
private shared sum as double

shared sub new()
counter = 0
sum = 0
end sub
public sub new(byval na as string, byval s as double)
emp_name = na
salary = s
counter = counter + 1
sum = sum + salary
end sub
shared function numberofobject() as integer
numberofobject = counter
end function
shared function average() as double
average = sum / counter
end function
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", 25000)
dim e2 as new employee("lily", 20000)
messagebox.show(str(e1.numberofobject()) + " objects")
messagebox.show("avgerage: " + str(e2.average()))
dim e3 as new employee("linda", 15000)
messagebox.show(str(e3.numberofobject()) + " objects")
messagebox.show("average: " + str(e3.average()))
end sub
end class

此程序输出:

2 objects
average: 22500
3 objects
average: 20000

还记得吗﹖一般程序成员是用来处理对象内的资料﹐所以呼叫一般程序成员之格式为──
对象. 一般程序成员

呼叫这程序成员的目的是来处理此对象之内容。共享程序成员之目的并非在于处理对象之内容﹐而是存取共享资料成员之值或处理些有关于整个类别的事情。因之﹐呼叫共享程序成员的格式为──

类别 . 共享程序成员

呼叫这共享程序成员之目的是来处理此类别之资料或有关之事情。
一种格式──
对象 . 共享程序成员

每个对象皆来自某个类别﹐vb看到对象名称时﹐可对应到它的类别﹐所
以vb在编译这种格式时﹐会将之转换成为﹕

类别 . 共享程序成员

亦即﹐指令── c1.nameofobject()
及 c2.nameofobject()

皆会转换成为-- employee.nameofobject()

同理﹐e1.average()也就相当于employee.average() 了。
由上述可知共享程序成员并非处理某个特定的对象值﹐所以没有必要去呼叫一般的程序成员。vb也就禁止共享程序成员呼叫一般的程序成员。不过﹐反之一般程序成员却可以呼叫共享程序成员﹐以便必要时可藉由共享程序成员来取得有关于整个类别的资料。例如:

'ex07.bas
imports system.componentmodel
imports system.drawing
imports system.winforms
'------------------------------------------------------------------------------
class employee
private emp_name as string
private salary as double

private shared counter as integer
private shared sum as double

shared sub new()
counter = 0
sum = 0
end sub
public sub new(byval na as string, byval s as double)
emp_name = na
salary = s
counter = counter + 1
me.sum = employee.sum + salary
end sub
public function getsalary() as double
getsalary = salary
end function
shared function numberofobject() as integer
numberofobject = counter
end function
shared function average() as double
dim k as double
average = employee.sum / employee.counter
' salary = salary + 2000 ' error!
' k = getsalary() ' error!
end function
public sub disp()
messagebox.show(str(employee.numberofobject()) + " objects")
messagebox.show("avgerage: " + str(employee.average()))
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", 25000)
dim e2 as new employee("lily", 20000)
e2.disp()
dim e3 as new employee("linda", 15000)
e3.disp()
end sub
end class

此程序输出:
2 objects
average: 22500
3 objects
average: 20000









共享程序,上述disp()是一般程序成员,此程序内的指令:

public sub disp()
messagebox.show(str(employee.numberofobject()) + " objects")
......
end sub

这就呼叫了共享的numberofobject()程序。
共享程序不可呼叫一般程序,上述average()是共享程序,它不能呼叫一般程序,所以average()内的指令有错:

shared function average() as double
dim k as double
average = employee.sum / employee.counter
' salary = salary + 2000 ' error!
' k = getsalary() ' error!
end function
请记得,共享程序是类别对象(妈妈)的程序,妈妈与小孩各有隐私(封装),小孩呼叫妈妈程序(即共享程序)的格式为:

妈妈 . 共享程序()
例如:employee.average()

或 对象 . 共享程序()
例如: e1.average() 或 me.average()。

但妈妈呼叫小孩程序的格式为:

对象 . 一般程序()
例如: e1.average()。

因为妈妈程序里没有me参考变量,所以上述的 k = getsalary()指令相当于k = me.getsalary(),就错掉了。请再看一个例子:


'ex08.bas
imports system.componentmodel
imports system.drawing
imports system.winforms
'--------------------------------------------------------------------------------
class employee
private emp_name as string
private salary as double

private shared counter as integer
private shared p(10) as employee

shared sub new()
counter = 0
end sub
public sub new(byval na as string, byval s as double)
emp_name = na
salary = s
p(counter) = me
counter = counter + 1
end sub
shared function getobject(byval index as integer) as employee
dim sp as employee
if index > counter or index < 0 then
sp = nothing
else
sp = p(index)
end if
getobject = sp
end function
public sub display()
messagebox.show("name: " + emp_name + " salary: " + str(salary))
end sub
shared sub disp(byval e as employee)
e.display()
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", 25000)
dim e2 as new employee("lily", 20000)

dim e3 as new employee("linda", 15000)
dim e4 as new employee("alvin", 5000)
dim emp as employee
emp = employee.getobject(2)
employee.disp( emp )
emp = employee.getobject(1)
employee.disp( emp )
end sub
end class


此程序输出:
name: linda salary: 15000
name: lily salary: 20000

在妈妈对象里有一个p(10)数组,每次诞生对象时,就将新对象的参考值存入数组里。妈妈程序getobject(i)则从数组中取出第i个对象,并传回来。妈妈程序使用格式:
对象 . 一般程序()

呼叫小孩的display()程序。
上述程序相当于:


'ex09.bas
imports system.componentmodel
imports system.drawing
imports system.winforms
'--------------------------------------------------------------------------------
class employee
private emp_name as string
private salary as double

private shared counter as integer
private shared p(10) as employee
private shared current as employee

shared sub new()
counter = 0
end sub
public sub new(byval na as string, byval s as double)
emp_name = na
salary = s
p(counter) = me
counter = counter + 1
end sub
shared sub findobject(byval index as integer)
dim sp as employee
if index > counter or index < 0 then
sp = nothing
else
sp = p(index)
end if
current = sp
end sub
shared sub disp()
messagebox.show( "name: " + current.emp_name +
" salary: " + str(current.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", 25000)
dim e2 as new employee("lily", 20000)

dim e3 as new employee("linda", 15000)
dim e4 as new employee("alvin", 5000)
employee.findobject(2)
employee.disp()
employee.findobject(1)
employee.disp()
end sub
end class


此程序输出:
name: linda salary: 15000
name: lily salary: 20000


妈妈程序findobject(i)则从数组中找到第i个对象,并记录在current变量里,不传回来。n

,欢迎访问网页设计爱好者web开发。
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表