简体   繁体   中英

Visual Basic .net - Call Procedure from a variable name

Is there a way to call a procedure in Visual Basic (.net) with a variable name?

For example, the variable strColour can be one of 10 pre-defined values, green blue black white red pink orange yellow indigo purple. How to handle each one is in it's own Sub Routine, colgreen, colblue, colblack and so on.

I can use a bunch of if..then..else and select case, but what I'd like to have is something like VBA Excel's Run "col" & strColour

Is it possible?

Private Sub Button1_Click(ByVal sender As System.Object, _
                          ByVal e As System.EventArgs) Handles Button1.Click
    Dim s As String = "one"
    CallByName(Me, s, CallType.Method) 'Subs must be public

    s = "two"
    CallByName(Me, s, CallType.Method) 'Subs must be public
End Sub

Public Sub one()
    Stop
End Sub

Public Sub two()
    Stop
End Sub

it is possible, by using reflection.

Dim thisType As Type = Me.GetType()
Dim theMethod As Reflection.MethodInfo = thisType.GetMethod("col" & strColour, Reflection.BindingFlags.NonPublic Or Reflection.BindingFlags.Instance)

If Not theMethod Is Nothing Then
    'this, if you have parameters
    theMethod.Invoke(Me, New Object() { add your parameters here, if any })
    'this, if you don't have parameters
    theMethod.Invoke(Me)
End If

I would use a select case unless you have a very large number of colours, or even better refactor those methods into 1 method. perhaps a generic one if necessary.

If there is no way to rewrite the color-handling sub-routines, then there is no good way to do it. You options:

  1. Reflection , which allows you to get the names of objects members (methods and properties). If your routines are on an object you can use this.
  2. Believe it or not, it is probably better to have a big select statement ! It looks inelegant, but will perform much better than using reflection.

Look into Reflection, it'll let you do what you want. However, in the end, the code will probably be about as complex as your select code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM