I am using Visual Studio 2005.
I want to get a function reference like what the AddressOf statement returns but my function name will be stored in a variable. Does anybody know a way of doing this?
Printable View
I am using Visual Studio 2005.
I want to get a function reference like what the AddressOf statement returns but my function name will be stored in a variable. Does anybody know a way of doing this?
At first sight it looks like you need to read about Reflection.
You need to declare a Delegate
A delegate is a type of variable that can hold a function (so long as the signature of that function matches the signature of the delegate declaration).
Here is a simple delegate example
VB Code:
Public Class Form1 Private Delegate Sub MyDelete(ByVal showText As String) Private Sub Form1_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load Dim oDelegateObject As New MyDelete(AddressOf MyDelegateCallback) oDelegateObject.Invoke("I am using a delegate!") End Sub Private Sub MyDelegateCallback(ByVal showText As String) MessageBox.Show(showText.Trim()) End Sub End Class
Vektor
That is not quite what I'm after. Say I had several functions that had the same interface as the delegate. How could I specify the function name as a string variable?
Perhaps if I gave a psudo-code example to explain what I mean:
VB Code:
Private Delegate Sub MyDelete(ByVal showText As String) Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim strFunctionName as String Dim oDelegateObject As MyDelete strFunctionName = "MyDelegateCallback" oDelegateObject = New MyDelete(AddressOf strFunctionName) oDelegateObject.Invoke("I am using a delegate!") End Sub Private Sub MyDelegateCallback(ByVal showText As String) MessageBox.Show(showText.Trim()) End Sub
NOTE: I need the function name to be a string variable because I will be getting it from an XML file.
Here's a simple example using a MethodInvoker delegate. You can quite easily substitute your own.VB Code:
Dim methodName As String Dim invoker As MethodInvoker = DirectCast([Delegate].CreateDelegate(GetType(MethodInvoker), Me.GetType(), methodName), MethodInvoker)
That looks like the one! Thanks. :)