简体   繁体   English

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

[英]Dynamically Invoke Method from method name string?

I have the following code: 我有以下代码:

 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()
    {

I will have many of these. 我将有许多。 They will all return a string and want to know if there is a way to avoid the switch case. 他们都将返回一个字符串,并想知道是否存在避免切换情况的方法。 If there is, is there a way to return "Not Found" if the method does not exist? 如果存在,如果该方法不存在,是否可以返回“找不到”?

Thanks 谢谢

Use reflection to obtain the methods: 使用反射获得方法:

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]);
}

This assumes that the methods you are calling will always have 0 arguments. 假设您正在调用的方法将始终具有0个参数。 If they have varying number of arguments you will have to adjust the array of parameters passed to MethodInfo.Invoke() accordingly. 如果它们具有不同数量的参数,则必须相应地调整传递给MethodInfo.Invoke()的参数数组。

GetMethod has several overloads. GetMethod有几个重载。 The one in this sample will return public methods only. 此示例中的一个将仅返回公共方法。 If you want to retrieve private methods, you need to call one of the overloads to GetMethod that accepts a BindingFlags parameter and pass BindingFlags.Private. 如果要检索私有方法,则需要调用GetMethod的重载之一,该重载接受BindingFlags参数并传递BindingFlags.Private。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM