Answers:
是。您可以使用反射。像这样:
Type thisType = this.GetType();
MethodInfo theMethod = thisType.GetMethod(TheCommandString);
theMethod.Invoke(this, userParameters);
Type thisType = this.GetType(); MethodInfo theMethod = thisType.GetMethod(TheCommandString, BindingFlags.NonPublic | BindingFlags.Instance); theMethod.Invoke(this, userParameters);
您可以使用反射来调用类实例的方法,并进行动态方法调用:
假设您在实际实例中有一个名为hello的方法(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);
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();
}
}
略有切线-如果要分析和评估包含(嵌套!)函数的整个表达式字符串,请考虑使用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
委托中,您将调用现有函数。
实际上,我正在Windows Workflow 4.5上工作,我找到了一种将委托从状态机传递给方法的方法,但没有成功。我唯一找到的方法是传递一个带有我想作为委托传递的方法名称的字符串,并将字符串转换为方法内部的委托。很好的答案。谢谢。检查此链接https://msdn.microsoft.com/en-us/library/53cz7sc6(v=vs.110).aspx
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();
}
}
在C#中,您可以将委托创建为函数指针。请查看以下MSDN文章,以获得有关用法的信息:http://msdn.microsoft.com/zh-CN/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 world to the console.
public
也应该如此。