【问题标题】:Templates In VBVB中的模板
【发布时间】:2008-09-08 13:33:55
【问题描述】:

我有一些 VB 代码(实际上是 VBA),除了它运行的类型之外,它们基本相同。因为我认为 DRY 原则是软件开发的一个很好的指导原则,所以我想为所有需要操作的不同类型编写一个例程。例如,如果我有两个这样的 sn-ps 代码:

Dim i as Obj1
Set i = RoutineThatReturnsObj1()
i.property = newvalue

Dim i as Obj2
Set i = RoutineThatReturnsObj2()
i.property = newvalue

我想要这样的东西来处理这两个实例:

Sub MyRoutine(o as ObjectType, r as RoutineToInitializeObject, newvalue as value) 
   Dim i as o
   Set i = r
   i.property = newvalue
End Sub

如果我使用 C++,我会生成一个模板,不再赘述。但我正在使用 VBA。我相当确定在 VBA 语言定义中没有像 C++ 模板这样的功能,但是有没有其他方法可以达到相同的效果?我猜答案是否定的,但我在这里问是因为我可能错过了 VBA 的某些功能。

【问题讨论】:

    标签: vba templates


    【解决方案1】:

    VB6 中没有任何东西可以做到这一点。如果您使用 .Net 更新到 Visual Studio Tools for Office,您可以使用泛型:

    Function MyRoutine(Of O)(R As Delegate, newvalue As Object) As O
        Dim i As O = CType(r.Method.Invoke(Nothing, Nothing), O)
    
        'you need another parameter to tell it which property to use'
        ' and then use reflection to set the value'
        i.property = newvalue 
        return i
    End Function
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-05
      • 1970-01-01
      • 1970-01-01
      • 2011-02-08
      • 1970-01-01
      • 2012-02-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多