VB中的模板

时间:2020-03-05 18:49:21  来源:igfitidea点击:

我有一些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