|
楼主 |
发表于 2012-5-6 17:31
|
显示全部楼层
继续,改装XYPoints类(最早只有一条语句Public x As Double, y As Double)
这里出现了一个新的关键字Get,顾名思义就是得到的意思。Let已经出现过了,但是这里的let又有点不同,这里的Let和Get你都把它看做是函数(过程),他们的目的就是为了操作类中的变量(也就是字段)。
Public x As Double, y As Double
Property Get Xpoint() As Double
Xpoint = x
End Property
Property Let Xpoint(xs As Double)
x = xs
End Property
Property Get Ypoint() As Double
Ypoint = y
End Property
Property Let Ypoint(ys As Double)
y = ys
End Property
这里注意了,Let函数(姑且称作过程或者函数)中是是有参数的。这个参数是等号右边传递给对象内部的。
如果
Dim a as new XYPoints
a. Xpoint = 12
单步F8运行就会看到调用过程
现在我们来试一试吧
此时在下面继续添加语句
Dim b As Double
b = a.Xpoint
MsgBox b
就会发现调用的是Get函数了
例子在附件中
Sub Test3()
Dim a As New XYpoint2
a.Xpoint = 12
Dim b As Double
b = a.Xpoint
MsgBox b
End Sub
接下去我们来分析如下代码:
Sub XYtest2()
Dim xyp As XYpoint2
Set xyp = New XYpoint2
xyp.Xpoint = 1
xyp.Ypoint = 9
MsgBox "x : " & xyp.Xpoint & vbCrLf & "y : " & xyp.Ypoint
End Sub
Sub XYtest3()
Dim xyp As XYpoint2
Set xyp = New XYpoint2
xyp.x = 1
xyp.y = 9
MsgBox "x : " & xyp.x & vbCrLf & "y : " & xyp.y
End Sub
Xypoint2类如下:
Public x As Double, y As Double
Property Get Xpoint() As Double
Xpoint = x
End Property
Property Let Xpoint(xs As Double)
x = xs
End Property
Property Get Ypoint() As Double
Ypoint = y
End Property
Property Let Ypoint(ys As Double)
y = ys
End Property
两者运行的结果是一样的。
既然如此那搞出Let和Set是要干嘛?
我们改变下类中变量的内容:
Private x As Double, y As Double
也就是把x y设置成私有的,所以你没有办法直接访问到x和y只能通过Let和Get了。
问题是这样做有意义吗?当然有,现在不讲。只要注意到关键字从Public变成Private就够了。再次总结下,Let Get 生来没别的,是用来操作类中的变量的。类中的变量也叫做字段,
存储的是类的属性。Let和Get与字段的关系好比是媒婆,没有她们你是见不到心爱的姑娘的(除非设置成Public),因为一般美女都是Private的。
运行后弹出如下错误:
现在我们修改下XYtest4
变成:
Sub XYtest5()
Dim xyp As XYpoint3
Set xyp = New XYpoint3
xyp.Xpoint = 1
xyp.Ypoint = 9
MsgBox "x : " & xyp.Xpoint & vbCrLf & "y : " & xyp.Ypoint
End Sub
这样就可以了
实际上从代码输入的过程中就能感知到变化:
当是Public x As Double, y As Double时候会弹出 x y字段的。
而当Private x As Double, y As Double时候就只弹出Let和Get了。
|
|