I know in php you are able to make a call like:
$function_name = 'hello';
$function_name();
function hello() { echo 'hello'; }
Is this possible in .Net?
I know in php you are able to make a call like:
$function_name = 'hello';
$function_name();
function hello() { echo 'hello'; }
Is this possible in .Net?
Yes. You can use reflection. Something like this:
Type thisType = this.GetType();
MethodInfo theMethod = thisType.GetMethod(TheCommandString);
theMethod.Invoke(this, userParameters);
In C#, you can create delegates as function pointers. Check out the following MSDN article for information on usage: http://msdn.microsoft.com/en-us/library/ms173171(VS.80).aspx
public static void hello()
{
Console.Write("hello world");
}
/* code snipped */
public delegate void functionPointer();
functionPointer foo = hello;
foo(); // Writes hello to the console.
class Program
{
static void Main(string[] args)
{
Type type = typeof(MyReflectionClass);
MethodInfo method = type.GetMethod("MyMethod");
MyReflectionClass c = new MyReflectionClass();
string result = (string)method.Invoke(c, null);
Console.WriteLine(result);
}
}
public class MyReflectionClass
{
public string MyMethod()
{
return DateTime.Now.ToString();
}
}
You can invoke methods of a class instance using reflection, doing a dynamic method invocation:
Suppose that you have a method called hello in a the actual instance (this):
string methodName = "hello";
//Get the method information using the method info class
MethodInfo mi = this.GetType().GetMethod(methodName);
//Invoke the method
// (null- no parameter for the method call
// or you can pass the array of parameters...)
mi.Invoke(this, null);