|
Calling subroutines by a variable name in Visual Basic.Net |
|
|
|
|
Written by J. Bijvoets
|
|
Thursday, 07 January 2010 21:00 |
|
If you want to call a subroutine in Visual Basic, life is simple: just type the procedurename, eventually followed by a parameter list between brackets... done!
But what if you want to call some procedure, and you don't know which procedure at design time, but you do in runtime? For example the procedure to be called is dependent on some selection the user makes, and you have stored in the database for each choice which procedure is to be called.
Well, life is still good with VB.Net. Do the following:
Define a Public class in which you put all the possible subroutines. Life is easier if you make all the parameter-lists in the same form.
Public Class clsCallSubroutineByVariableDemo
Public Sub subDemo1 (ByVal s As String)
MsgBox("Called subDemo1 with parameter=" & s)
End Sub
Public Sub subDemo2 (ByVal s As String)
MsgBox("Called subDemo2 with parameter=" & s)
End Sub
Public Sub subDemo3 (ByVal s As String)
MsgBox("Called subDemo3 with parameter=" & s)
End Sub
End Class
You can call all these subroutines with their name stored in a variable with the following code:
Public Sub CallASub(ByVal sSubroutine As String, ByVal sSomeParameter As String)
Dim MyObj As New clsCallSubroutineByVariableDemo Dim myType As System.Type = GetType(CallingDemo) Dim myInfo As System.Reflection.MethodInfo = myType.GetMethod(sSubroutine) Dim myParameters() As Object = {sSomeParameter} myInfo.Invoke(MyObj, myParameters)
End Sub
You can call this function with the following:
CallASub("subDemo1", "Some interesting parameter for testing purposes!")
Don't get encouraged if the first test is not working, as I was disappointed already for you during my first test of this code (at least for a minute). The code works really fine, but the function GetMethod wants you to enter the routine name in the right upper- and lowercase. So the code CallASub("subdemo1", "test") doesn't work.
|
|
Last Updated on Sunday, 28 November 2010 09:22 |