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

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 的某些功能。

有帮助吗?

解决方案

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
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top