从方法名称字符串动态调用方法

本文关键字:方法 动态 调用 字符串 | 更新日期: 2023-09-27 18:01:32

我有以下代码:

 public string GetResponse()
    {
        string fileName = this.Page.Request.PathInfo;
        fileName = fileName.Remove(0, fileName.LastIndexOf("/") + 1);
        switch (fileName)
        {
            case "GetEmployees":
                return GetEmployees();
            default:
                return "";
        }
    }
    public string GetEmployees()
    {

我要吃很多。它们都将返回一个字符串,并且想知道是否有办法避免切换情况。如果有,如果方法不存在,是否有方法返回"Not Found"?

谢谢

从方法名称字符串动态调用方法

使用反射获取方法:

public string GetResponse()
{
    string fileName = this.Page.Request.PathInfo;
    fileName = fileName.Remove(0, fileName.LastIndexOf("/") + 1);
    MethodInfo method = this.GetType().GetMethod(fileName);
    if (method == null)
        throw new InvalidOperationException(
            string.Format("Unknown method {0}.", fileName));
    return (string) method.Invoke(this, new object[0]);
}

这假设您调用的方法总是有0个参数。如果它们具有不同数量的参数,则必须相应地调整传递给MethodInfo.Invoke()的参数数组。

GetMethod有几个重载。本示例中的示例将只返回公共方法。如果你想检索私有方法,你需要调用GetMethod的一个重载,它接受一个BindingFlags参数,并传递BindingFlags. private .

相关文章: