我知道在 php 中你可以拨打如下电话:
$function_name = 'hello';
$function_name();
function hello() { echo 'hello'; }
这在.Net中可能吗?
我知道在 php 中你可以拨打如下电话:
$function_name = 'hello';
$function_name();
function hello() { echo 'hello'; }
这在.Net中可能吗?
是的。您可以使用反射。像这样的东西:
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);
您可以使用反射调用类实例的方法,执行动态方法调用:
假设您在实际实例 (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);
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();
}
}
class Program
{
static void Main(string[] args)
{
string method = args[0]; // get name method
CallMethod(method);
}
public static void CallMethod(string method)
{
try
{
Type type = typeof(Program);
MethodInfo methodInfo = type.GetMethod(method);
methodInfo.Invoke(method, null);
}
catch(Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
Console.ReadKey();
}
}
public static void Hello()
{
string a = "hello world!";
Console.WriteLine(a);
Console.ReadKey();
}
}
有点切线 - 如果您想解析和评估包含(嵌套!)函数的整个表达式字符串,请考虑 NCalc(http://ncalc.codeplex.com/和 nuget)
前任。对项目文档稍作修改:
// the expression to evaluate, e.g. from user input (like a calculator program, hint hint college students)
var exprStr = "10 + MyFunction(3, 6)";
Expression e = new Expression(exprString);
// tell it how to handle your custom function
e.EvaluateFunction += delegate(string name, FunctionArgs args) {
if (name == "MyFunction")
args.Result = (int)args.Parameters[0].Evaluate() + (int)args.Parameters[1].Evaluate();
};
// confirm it worked
Debug.Assert(19 == e.Evaluate());
在EvaluateFunction
委托中,您将调用您现有的函数。