Public Property Get CustomerID() As String
CustomerID = rs("CustomerID")
End Property
Public Property Let CustomerID(NewValue As String)
rs("CustomerID") = NewValue
End Property
显然,该属性的Get操作只是简单地返回"CustomerID"字段的值,相应地,Let操作是将"CustomerID"字段设置一个新值。
换句话说,属性中有两个部分:"getting"和"letting",事实上可能还有另外一个"setting"操作。但对于不同场合来说,我们总需要Get和Let来进行读和写的操作。
这里所引起注意的是,在上述属性过程中,应该对某些值进行必要的检测。例如,在调用Let属性时,用户可能有如下操作:
ObjectName.CustomerID = "HALFI"
该Let属性操作后,"CustomerID"等于新的字符串"HALFI"。但当查看Northwind数据库内容时,我们会发现"CustomerID"字段的字符长度不能超过5。如果用户有这样的操作:
ObjectName.CustomerID = "HALFISTORE"
则出现数据库操作错误。虽然,可以通过错误句柄来处理这个问题,但是如果能在代码中检测NewValue的长度岂不更好?如果该值超过5个字符,我们既可以通过裁剪取共前5个字符,也可以忽略这个新的字符串而弹出一个错误提示。但这里,我们采用后一种措施。
在我们的类中添加下列代码:
Public Property Get CustomerID() As String
CustomerID = rs("CustomerID")
End Property
Public Property Let CustomerID(NewValue As String)
'If the length of NewValue is greater than five
If Len(NewValue) > 5 Then
'... then raise an error to the program
'using this class
Err.Raise VBObjectError 1, "CustomerID", _"Customer ID can only be up to five " & _"characters long!"
Else
'... otherwise, change the field value
rs("CustomerID") = NewValue
End If
End Property
好了,在完成下列步骤之前,我们已经为添加方法花费了不少时间。
在我们的类中添加下列代码:
Public Sub Update()
rs.Update
End Sub
该Update方法只是简单地调用记录集对象的Update方法来更新记录。
下一步,我们将用一个很小的样例程序来测试这个属性和方法,在测试时还将使用特定的技巧来追踪类和程序的运行。
上一篇: VB COM基础讲座之创建第一个COM对象
下一篇: VB COM基础讲座之可重用性
文章整理:西部数码--专业提供域名注册、虚拟主机服务
http://www.west263.com
以上信息与文章正文是不可分割的一部分,如果您要转载本文章,请保留以上信息,谢谢!




