您的位置:首页 > 编程语言 > VB

VB COM基础讲座之添加属性和方法

2004-11-02 09:49 357 查看
下面,我们添加一个属性来让用户获取CustomerID字段的值,其相应的示例代码如下:

  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方法来更新记录。

  下一步,我们将用一个很小的样例程序来测试这个属性和方法,在测试时还将使用特定的技巧来追踪类和程序的运行。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息