Dynamically call a function depending on the value of a variable

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I am using a treeview and within each node, I want to store the name of the
function that was called to create the node's data.

Then whenever a user selects this node, I want to be able to call that
function without having to create a huge SELECT CASE statement.

i.e.

Node.123's data is created in a function called "fnGetProjectDetails"

I want to be able to use say the node.tag field to store "fnGetProjectDetails"

and then when that node is selected to be able to simply call node.tag to
refresh the data.

I am still a rookie with .NET, so please go easy with me !

Is this possible?
 
Rather than storing the text name of the function, store a delegate instead.

A delegate is a type that refers to a method. The EventHandler delegate is
probably the best known (for Win Form developers at least), although you will
probably not be aware you are using them.

Google/MSDN can probably provide much better guidance for you then I can,
but hopefully this will point you in the right direction.

Dan
 
You did not say what language you are using but here is an example in C# of
how to do what you would like to do. You can call any method of any class
using reflection.

// create an instance of the class containing the function to execute
Foo myClass = new Foo();

// get the class type
Type myType = myClass.GetType();

// get the method you want to invoke ("myMethod" can be a string variable)
System.Reflection.MethodInfo myMethod = t.GetMethod("myMethod");

// create an object array with the parameter values for the function call
// if these are variable there are more reflection methods to get the list of
// of parameters for the function
object[] myParams = new object["Param1", "ParamEct"];

// invoke the method
object retValue = myMethod.Invoke(myClass, myParams);

I hope this helps.

Greg
 
Sorry. The one line in the example has a typo;

Was:
// get the method you want to invoke ("myMethod" can be a string variable)
System.Reflection.MethodInfo myMethod = t.GetMethod("myMethod");

Should Be:
// get the method you want to invoke ("myMethod" can be a string variable)
System.Reflection.MethodInfo myMethod = myType.GetMethod("myMethod");

Greg
 
Back
Top