下面,我們添加一個屬性來讓用戶獲取CustomerID字段的值,其相應(yīng)的示例代碼如下:
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"字段的值,相應(yīng)地,Let操作是將"CustomerID"字段設(shè)置一個新值。
換句話說,屬性中有兩個部分:"getting"和"letting",事實(shí)上可能還有另外一個"setting"操作。但對于不同場合來說,我們總需要Get和Let來進(jìn)行讀和寫的操作。
這里所引起注意的是,在上述屬性過程中,應(yīng)該對某些值進(jìn)行必要的檢測。例如,在調(diào)用Let屬性時,用戶可能有如下操作:
ObjectName.CustomerID = "HALFI"
該Let屬性操作后,"CustomerID"等于新的字符串"HALFI"。但當(dāng)查看Northwind數(shù)據(jù)庫內(nèi)容時,我們會發(fā)現(xiàn)"CustomerID"字段的字符長度不能超過5。如果用戶有這樣的操作:
ObjectName.CustomerID = "HALFISTORE"
則出現(xiàn)數(shù)據(jù)庫操作錯誤。雖然,可以通過錯誤句柄來處理這個問題,但是如果能在代碼中檢測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
好了,在完成下列步驟之前,我們已經(jīng)為添加方法花費(fèi)了不少時間。
在我們的類中添加下列代碼:
Public Sub Update()
rs.Update
End Sub
該Update方法只是簡單地調(diào)用記錄集對象的Update方法來更新記錄。
下一步,我們將用一個很小的樣例程序來測試這個屬性和方法,在測試時還將使用特定的技巧來追蹤類和程序的運(yùn)行。
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"字段的值,相應(yīng)地,Let操作是將"CustomerID"字段設(shè)置一個新值。
換句話說,屬性中有兩個部分:"getting"和"letting",事實(shí)上可能還有另外一個"setting"操作。但對于不同場合來說,我們總需要Get和Let來進(jìn)行讀和寫的操作。
這里所引起注意的是,在上述屬性過程中,應(yīng)該對某些值進(jìn)行必要的檢測。例如,在調(diào)用Let屬性時,用戶可能有如下操作:
ObjectName.CustomerID = "HALFI"
該Let屬性操作后,"CustomerID"等于新的字符串"HALFI"。但當(dāng)查看Northwind數(shù)據(jù)庫內(nèi)容時,我們會發(fā)現(xiàn)"CustomerID"字段的字符長度不能超過5。如果用戶有這樣的操作:
ObjectName.CustomerID = "HALFISTORE"
則出現(xiàn)數(shù)據(jù)庫操作錯誤。雖然,可以通過錯誤句柄來處理這個問題,但是如果能在代碼中檢測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
好了,在完成下列步驟之前,我們已經(jīng)為添加方法花費(fèi)了不少時間。
在我們的類中添加下列代碼:
Public Sub Update()
rs.Update
End Sub
該Update方法只是簡單地調(diào)用記錄集對象的Update方法來更新記錄。
下一步,我們將用一個很小的樣例程序來測試這個屬性和方法,在測試時還將使用特定的技巧來追蹤類和程序的運(yùn)行。

