【问题标题】:Calling a function from a string in C#从 C# 中的字符串调用函数
【发布时间】:2009-02-12 04:49:29
【问题描述】:

我知道在 php 中你可以这样调用:

$function_name = 'hello';
$function_name();

function hello() { echo 'hello'; }

这在 .Net 中可行吗?

【问题讨论】:

    标签: c# .net php string function-calls


    【解决方案1】:

    是的。您可以使用反射。像这样的:

    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);
    

    【讨论】:

      【解决方案2】:

      您可以使用反射调用类实例的方法,进行动态方法调用:

      假设您在实际实例 (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);
      

      【讨论】:

        【解决方案3】:
        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();
                }
            }
        

        【讨论】:

          【解决方案4】:
          此代码适用于我的控制台 .Net 应用程序
          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();
              }
          }
          

          【讨论】:

            【解决方案5】:

            有点切题 - 如果您想解析和评估包含(嵌套!)函数的整个表达式字符串,请考虑 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 委托中,您可以调用现有函数。

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2013-10-26
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多