开发者

How to call a function with function name reference to a string value in VB

开发者 https://www.devze.com 2022-12-26 10:24 出处:网络
I have this algorithm that I want to implement on VB6. Sub Main() dim stringVal1 as string, stringVal2 as string

I have this algorithm that I want to implement on 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?**
开发者_JAVA技巧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

Can this be done in VB6?


Generally, such code patterns point to errors in your software design.

In the rare cases where this is really needed, CallByName accomplishes this.

Example:

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


It would help if you give more information about why you're needing to call functions by the string representation of their name. Could you not simply re-write your code like this:

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


Generally, you don't want to actually dispatch based on Strings. This is error-prone (as you have to be really sure at run time that your String has the function name you want), and really unnecessary. The way to do this sort of thing where you want to be able to "pass in" the method that you want to use would be to use the polymorphism that VB has, and use a separate Class for each implementation.

In the Class Module that you use for your interface, say named MyInterface:

Public Sub DoStuff()
End Sub

Then, create two Class Modules, one for each possible implementation of the Interface:

In MyClassOne:

Implements MyInterface
Public Sub MyInterface_DoStuff()
    Msgbox "I'm function one"
End Sub

Then, in MyClassTwo, the same thing but with your other implementation:

Implements MyInterface
Public Sub MyInterface_DoStuff()
    Msgbox "I'm function two"
End Sub

To use it, you just need to pass in which implementation you want to use:

Private Sub UseInterface(WhichThingToUse as MyInterface)
  WhichThingToUse.DoStuff
End Sub

Rather than using a String variable to store which method to use, you need to instead store a New MyClassOne or a New MyClassTwo. You don't show how your getOne variable gets set, but whatever the logic is for it, you just need to change to store an instance of MyInterface instead, and just use that directly.

For further reading in the MSDN library:

  • How Visual Basic Provides Polymorphism
  • Creating and Implementing an Interface
  • Creating Interfaces for Use With the Implements Statement
  • Implements Statement reference
0

精彩评论

暂无评论...
验证码 换一张
取 消