2

我有一种情况,我想将对象类型作为比较逻辑的参数传递。

例子:

Sub Some (val as Control, typ as Type, ....)
   ...
   if typeof val is typ then
      ...
   end if
   ...
End Sub

我发现自己在多种方法中执行此逻辑模式,并希望将逻辑浓缩到一个位置而不是多个位置,以简化操作。

这是验证这种结构的正确方法还是有更好的方法来做这些事情?

4

1 回答 1

0

这并没有花很长时间

如果您想将比较抽象为通用的,这应该可以让您找到正确的逻辑。

Public Sub CompareType(val as Control, typ as String)
   ...
   if TypeName(val) = typ then
      ...
   end if
   ...
End Sub

基本上传递对象(val),如果您想进一步抽象,可以是变体,然后如果您知道将为该类型返回的字符串值,然后将其作为字符串值传递

工作示例:

在代码运行中:

...
AutoSizeControl CurrentDb, frm, "Textbox"
...

模块声明:

Public Sub AutoSizeControl(ByRef db As Database, ByRef frm As Form, typ As String)
    Dim ctl As Control, i As Integer
    For i = 0 To (frm.Controls.Count - 1)
        Set ctl = frm.Controls(i)
        If TypeName(ctrl) = typ Then
            ctl.ColumnWidth = -2
        End If
    Next
End Sub

希望这可以帮助其他可能需要这种抽象的人。

于 2012-08-17T14:33:19.150 回答