Execute a function using it's name as string
A collegue asked me if it was possible to call a function when you only have a string with the name of the function.
Of course, this is possible in .NET, everything is ;-)
This is the little test-project I created for him in VB.NET.
Private Function test1() As String
Return Now.ToString("dd/MM/yyyy HH:mm:ss")
End Function
Private Function test2(ByVal string1 As String, ByVal integer1 As Integer) As String
Return Convert.ToString(integer1) & string1
End Function
Private Function CallFunctionByName(ByVal name As String, ByVal parameters As Object()) As Object
Return Me.GetType.GetMethod(name, BindingFlags.NonPublic Or BindingFlags.Public Or BindingFlags.Static Or BindingFlags.Instance).Invoke(Me, parameters)
End Function
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Button1.Text = Convert.ToString(CallFunctionByName("test1", Nothing))
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim p As Object() = New Object(1) {}
p(0) = "test"
p(1) = 14
Button2.Text = Convert.ToString(CallFunctionByName("test2", p))
End Sub
Pretty easy, isn' t it?
Of course, this is possible in .NET, everything is ;-)
This is the little test-project I created for him in VB.NET.
- Add two buttons to a form
- Add these two function in code:
Private Function test1() As String
Return Now.ToString("dd/MM/yyyy HH:mm:ss")
End Function
Private Function test2(ByVal string1 As String, ByVal integer1 As Integer) As String
Return Convert.ToString(integer1) & string1
End Function
- Add this main function:
Private Function CallFunctionByName(ByVal name As String, ByVal parameters As Object()) As Object
Return Me.GetType.GetMethod(name, BindingFlags.NonPublic Or BindingFlags.Public Or BindingFlags.Static Or BindingFlags.Instance).Invoke(Me, parameters)
End Function
- Add the click-events of the two buttons:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Button1.Text = Convert.ToString(CallFunctionByName("test1", Nothing))
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim p As Object() = New Object(1) {}
p(0) = "test"
p(1) = 14
Button2.Text = Convert.ToString(CallFunctionByName("test2", p))
End Sub
Pretty easy, isn' t it?
0 Comments:
Post a Comment
<< Home