运行名称作为字符串传递的方法

Gav*_*vin 5 c#

我有一个C#方法,它接受一个字符串作为参数,该字符串包含静态方法的名称,例如

"MyClass.GetData"
Run Code Online (Sandbox Code Playgroud)

是否可以从字符串中传递的值运行该方法?

Hat*_*ath 12

是的,你可以使用System.Reflection


CallStaticMethod("MainApplication.Test", "Test1");

public  static void CallStaticMethod(string typeName, string methodName)
{
    var type = Type.GetType(typeName);

    if (type != null)
    {
        var method = type.GetMethod(methodName);

        if (method != null)
        {
            method.Invoke(null, null);
        }
    }
}

public static class Test
{
    public static void Test1()
    {
        Console.WriteLine("Test invoked");
    }
}
Run Code Online (Sandbox Code Playgroud)