Vb6 如何在VB中调用函数名引用字符串值的函数

Vb6 如何在VB中调用函数名引用字符串值的函数,vb6,Vb6,我想在VB6上实现这个算法 Sub Main() dim stringVal1 as string, stringVal2 as string dim getOne as boolean stringVal1 = "FunctOne" stringVal2 = "FunctTwo" if getOne then 'Call Function with function name assigned to stringVal1 ... how to call the function h

我想在VB6上实现这个算法

Sub Main()
dim stringVal1 as string, stringVal2 as string
dim getOne as boolean

stringVal1 = "FunctOne"
stringVal2 = "FunctTwo"

if getOne then
    'Call Function with function name assigned to stringVal1 ... how to call the function here?**
else
    'Call Function with function name assigned to stringVal1 ... how to call the function here?**
end if

End Sub


Function FunctOne()
   Msgbox "I'm function one"
End Function

Function FunctTwo()
   Msgbox "I'm function two"
End Function

这可以在VB6中完成吗?

通常,这样的代码模式指向软件设计中的错误

在极少数确实需要这样做的情况下,
CallByName
可以实现这一点

例如:

Call CallByName(Me, "NameOfFunction", vbMethod, arguments)

如果您提供更多关于为什么需要通过函数名称的字符串表示来调用函数的信息,这会有所帮助。您能不能不简单地像这样重新编写代码:

If getOne Then 
    Call FuncOne()
Else 
    Call FuncTwo() 
End If

通常,您不希望实际基于字符串进行调度。这很容易出错(因为您必须在运行时真正确保字符串具有所需的函数名),而且确实不必要。要做到这一点,您希望能够“传入”您想要使用的方法,可以使用VB拥有的多态性,并为每个实现使用单独的类

在用于接口的类模块中,说named
MyInterface

Public Sub DoStuff()
End Sub
然后,创建两个类模块,一个用于接口的每个可能实现:

MyClassOne
中:

Implements MyInterface
Public Sub MyInterface_DoStuff()
    Msgbox "I'm function one"
End Sub
然后,在
MyClassTwo
中,与您的其他实现相同:

Implements MyInterface
Public Sub MyInterface_DoStuff()
    Msgbox "I'm function two"
End Sub
要使用它,您只需传入要使用的实现:

Private Sub UseInterface(WhichThingToUse as MyInterface)
  WhichThingToUse.DoStuff
End Sub
与使用字符串变量存储要使用的方法不同,您需要存储一个
newmyclassone
或一个
newmyclasstwo
。您不会显示如何设置
getOne
变量,但不管它的逻辑是什么,您只需要更改以存储MyInterface的实例,并直接使用它

如需在MSDN库中进一步阅读:


AFAIK这是在vb6@Andrey:不,你完全错了:VB6知道接口()。此外,VB6支持开箱即用的后期绑定,因此您可以只调用多态对象上的方法(但这不再适用于
Option Explicit
)。@Konrad+1供您回答和评论。不过还有一个小问题:后期绑定仍然适用于
选项Explicit
?@MarkJ:是吗?显然,我已经很久没有使用VB6了-(@Andrey也许如果你如此讨厌VB6,你就不应该对VB6的问题发表评论