代码之家  ›  专栏  ›  技术社区  ›  Onorio Catenacci

VB中的模板

  •  2
  • Onorio Catenacci  · 技术社区  · 17 年前

    我有一些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的一些功能。

    1 回复  |  直到 11 年前
        1
  •  1
  •   Joel Coehoorn    17 年前

    在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