155

我知道在 php 中你可以拨打如下电话:

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

function hello() { echo 'hello'; }

这在.Net中可能吗?

4

5 回答 5

292

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

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-12T04:53:33.297 回答
80

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

假设您在实际实例 (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-12T04:57:56.063 回答
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();
        }
    }
于 2009-02-12T04:57:39.980 回答
3
此代码适用于我的控制台 .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();
    }
}
于 2020-07-14T22:10:42.077 回答
2

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

于 2014-12-05T15:58:12.903 回答