从C#中的字符串调用函数

Jer*_*oyd 139 .net php c# string function-calls

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

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

function hello() { echo 'hello'; }
Run Code Online (Sandbox Code Playgroud)

这可能在.Net吗?

ott*_*bar 258

是.你可以使用反射.像这样的东西:

Type thisType = this.GetType();
MethodInfo theMethod = thisType.GetMethod(TheCommandString);
theMethod.Invoke(this, userParameters);
Run Code Online (Sandbox Code Playgroud)

  • 这需要"使用System.Reflection"; (50认同)

CMS*_*CMS 71

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

假设您在实际实例中有一个名为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);
Run Code Online (Sandbox Code Playgroud)


BFr*_*ree 36

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();
        }
    }
Run Code Online (Sandbox Code Playgroud)