[C#] 通过方法的字符串名动态调用方法

使用这个方法的目的是减少code:

public class MyClass
{
    public string func1()
    {
        return "func1";
    }
    public string func2()
    {
        return "func2";
    }
    public string func3()
    {
        return "func3";
    }
    public string func4()
    {
        return "func4";
    }
    public void callFunc(string funcName)
    {
        MethodInfo method = GetType().GetMethod(funcName);
        Func<string> func = (Func<string>)Delegate.CreateDelegate(typeof(Func<string>), this, method);
        Console.Write(func() + " ");
    }
}

测试:

static void Main(string[] args)
{
    try
    {
        MyClass obj = new MyClass();
        for (int i = 1; i <= 4; i++)
        {
            string functionName = "func" + i;
            obj.callFunc(functionName);
        }
    }
    catch (Exception exp)
    {
        Console.WriteLine(exp.Message);
    }
}

输出如下:

func1 func2 func3 func4

[1] https://stackoverflow.com/questions/15142885/dynamically-invoke-method-from-method-name-string

猜你喜欢

转载自blog.csdn.net/ftell/article/details/81745908