日期:2012-11-03  浏览次数:20385 次

1. 使用Me参考值
1.1 认识Me参考值

类别之程序成员(Procedure Member) 各含一个Me参考变量﹐它永远参考到「目前对象」(Current Object)。目前对象就是正接受并处理讯息之对象。例如﹐

'ex01.bas
Imports System.ComponentModel
Imports System.Drawing
Imports System.WinForms
'------------------------------------------------------------------------------
Public Class Fee
Private amount As Decimal

Public Sub New(ByVal amt As Decimal)
Me.amount = amt
End Sub
Public Sub disp()
MessageBox.Show("Amount is " + str( Me.amount ))
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 Fee(100)
Dim b As New Fee(80)
a.disp()
b.disp()
End Sub
End Class

此程序输出如下﹕Amount is 100
Amount is 80


a 和 b是Fee类别之对象。当计算机执行指令──
a.disp()

a 就是目前对象﹐disp()程序里的Me正参考到对象a。


也可看成:

图1、 Me参考值与目前对象

请注意﹕Me参考到对象a﹐也就是Me与a皆参考到同一个对象。
当计算机执行另一指令── b.disp()时,b 即为目前对象﹐而disp()程序之Me参考正指向对象 b。


由于Me正参考到对象b﹐所以Me与b参考到同一个对象。写程序时﹐宜充分利用Me参考。



1.2 程序传回Me参考值

在应用上﹐程序常传回Me参考值﹐可创造奇妙的效果﹐这种效果也是VB的重要特色。希望您能仔细了解Me指针之使用场合﹐能让您写出完美的OOP程序来﹗现在﹐请看个熟悉的程序──

'ex02.bas
Imports System.ComponentModel
Imports System.Drawing
Imports System.WinForms
'------------------------------------------------------------------------------
Public Class Money
Private balance As Decimal
Public Sub New(ByVal amount As Decimal)
balance = amount
End Sub
Public Sub add(ByVal saving As Decimal)
balance = balance + saving
End Sub
Public Sub Display()
MessageBox.Show("Balance is " + str(balance))
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 orange As New Money(100)
orange.add(300)
orange.add(80)
orange.Display()
End Sub
End Class

此程序输出如下﹕Balance is 480

Money 类别的 balance资料﹐记录存款余额。main()内之对象orange接受两讯息──add(300)及add(80) ﹐欲存入两项金额。



指令── orange.add(300)
orange.add(80)

表示﹕先存入 300元再存入80元﹐有先后次序。若上述图形改为──



则更具次序感。于是﹐上述指令相当于──



这种效果﹐不太陌生吧﹗回忆小学