ITPub博客

首页 > 应用开发 > IT综合 > VB COM基础讲座之添加属性和方法(转)

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

原创 IT综合 作者:BugRobber 时间:2007-07-08 11:04:17 0 删除 编辑
下面,我们添加一个属性来让用户获取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方法来更新记录。

   下一步,我们将用一个很小的样例程序来测试这个属性和方法,在测试时还将使用特定的技巧来追踪类和程序的运行。[@more@]

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/8781179/viewspace-925174/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论
  • 博文量
    372
  • 访问量
    200898