使用表达式获取方法的名称 [英] Get the name of a method using an expression
问题描述
我知道这个网站上有一些答案,如果这有任何重复,我深表歉意,但我发现的所有答案都没有做我想做的.
I know there are a few answers on the site on this and i apologize if this is in any way duplicate, but all of the ones I found does not do what I am trying to do.
我正在尝试指定方法信息,以便我可以通过不使用字符串以类型安全的方式获取名称.所以我想用一个表达式来提取它.
I am trying to specify method info so I can get the name in a type safe way by not using strings. So I am trying to extract it with an expression.
说我想得到这个接口中的一个方法的名字:
Say I want to get the name of a method in this interface:
public interface IMyInteface
{
void DoSomething(string param1, string param2);
}
目前我可以使用此方法获取名称:
Currently I can get the name using THIS method:
MemberInfo GetMethodInfo<T>(Expression<Action<T>> expression)
{
return ((MethodCallExpression)expression.Body).Method;
}
我可以按如下方式调用辅助方法:
I can call the helper method as follows:
var methodInfo = GetMethodInfo<IMyInteface>(x => x.DoSomething(null, null));
Console.WriteLine(methodInfo.Name);
但是我在找不指定参数就可以获取方法名的版本(null,null)
But I am looking for the version that I can get the method name without specifying the parameters (null, null)
像这样:
var methodInfo = GetMethodInfo<IMyInteface>(x => x.DoSomething);
但所有尝试都编译失败
有没有办法做到这一点?
Is there a way to do this?
推荐答案
x => x.DoSomething
为了使其可编译,我只看到两种方法:
In order to make this compilable I see only two ways:
- 采用非通用方式并将其参数指定为
Action
- 自己指定
Action
作为你的目标委托类型:GetMethodInfo
(x => new Action (x.DoSomething))
- Go non-generic way and specify it's parameter as
Action<string, string>
- Specify
Action<string, string>
as your target delegate type by yourself:GetMethodInfo<IMyInteface>(x => new Action<string,string>(x.DoSomething))
如果你可以使用第二个,它允许你省略参数,那么你可以编写你的 GetMethodInfo
方法如下:
if you are ok to go with second one, which allows you to omit arguments then you can write your GetMethodInfo
method as follows:
MemberInfo GetMethodInfo<T>(Expression<Func<T, Delegate>> expression)
{
var unaryExpression = (UnaryExpression) expression.Body;
var methodCallExpression = (MethodCallExpression) unaryExpression.Operand;
var methodInfoExpression = (ConstantExpression) methodCallExpression.Arguments.Last();
var methodInfo = (MemberInfo) methodInfoExpression.Value;
return methodInfo;
}
它适用于您的界面,但可能需要进行一些概括才能使其适用于任何方法,这取决于您.
It works for your interface, but probably some generalization will be required to make this working with any method, that's up to you.
这篇关于使用表达式获取方法的名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!