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

前端 未结 3 1778
眼角桃花
眼角桃花 2020-12-21 18:53

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 = \"FunctO         


        
相关标签:
3条回答
  • 2020-12-21 19:27

    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 讨论(0)
  • 2020-12-21 19:30

    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
    
    0 讨论(0)
  • 2020-12-21 19:44

    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)
    
    0 讨论(0)
提交回复
热议问题