我知道在php中你可以这样调用:
$function_name = 'hello';
$function_name();
function hello() { echo 'hello'; }
这在.Net中是可能的吗?
发布于 2009-02-12 04:53:33
是。您可以使用反射。如下所示:
Type thisType = this.GetType();
MethodInfo theMethod = thisType.GetMethod(TheCommandString);
theMethod.Invoke(this, userParameters);
使用上面的代码,被调用的方法必须有访问修饰符public
。如果调用非公共方法,则需要使用BindingFlags
参数,例如BindingFlags.NonPublic | BindingFlags.Instance
Type thisType = this.GetType();
MethodInfo theMethod = thisType
.GetMethod(TheCommandString, BindingFlags.NonPublic | BindingFlags.Instance);
theMethod.Invoke(this, userParameters);
发布于 2009-02-12 04:57:56
您可以使用反射调用类实例的方法,执行动态方法调用:
假设您在实际实例(This)中有一个名为hello的方法:
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);
发布于 2009-02-12 04:57:40
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();
}
}
https://stackoverflow.com/questions/540066
复制相似问题