将方法转换为“System”.委托'为动作名称获取' MethodInfo '

本文关键字:MethodInfo 获取 转换 System 委托 方法 | 更新日期: 2023-09-27 18:02:58

我正在尝试将方法转换为System.Delegate:

Delegate method = (Delegate)MyMethod;

但这不起作用,因为我得到一个异常告诉我MyMethod不能转换为非委托类型。

我如何从一个方法得到一个通用的System.Delegate ?

目的是得到该方法的MethodInfo.Name。所以我基本上想要以"强类型方式"的字符串形式获得方法名。我想为MVC创建一个像下面这样的助手:

protected internal RedirectToRouteResult RedirectToAction(Func<ActionResult> action)
{ 
    return RedirectToAction(action.Method.Name);
}

然后我可以调用例如return RedirectToAction(Index);而不是return RedirectToAction("Index"),因此请参阅Index的参考资料,并在编译时检查动作是否存在。但是上面的helper代码只适用于无参数的操作,所以我希望它适用于具有任何类型参数的操作,而不需要为每个可能的参数群指定重载。

将方法转换为“System”.委托'为动作名称获取' MethodInfo '

使用委托。CreateDelegate

Func<string, string> funcToConvert = testMethod;
var del = Delegate.CreateDelegate(funcToConvert.GetType(), funcToConvert.Method);
var name = del.Method.Name;