从LINQ表达式提取方法名 [英] extracting method name from linq expression
问题描述
我怎样才能获得在C#中的表达式称为第一方法的名称?像虚构的 MethodUtils.NameFromExpression()的如下:
How can I get the name of the first method called from an expression in C#? Something like the fictional MethodUtils.NameFromExpression() below:
Expression<Action<string>> expr = s => s.Trim();
Assert.AreEqual("Trim", MethodUtils.NameFromExpression(expr));
理想情况下任何util的方法将被写入/重载以这样一种方式,它可以采取表达式为任何的操作或FUNC。委托类型。
Ideally any util method would be written/overloaded in such a way that it could take expressions for any of the Action or Func delegate types.
在此先感谢。
更新
我找到了答案(下同),但仍希望投入,这是否是一个很好的解决方案,或者是否有已经存在于BCL这样做的方式。
I found an answer (below) but would still like input as to whether this is a good solution or whether there already exists a way of doing this in the BCL.
推荐答案
和我使用调试器挖的位已经回答了我的问题:
A bit of digging with the debugger and I've answered my own question:
public static class MethodUtils
{
public static string NameFromExpression(LambdaExpression expression)
{
MethodCallExpression callExpression =
expression.Body as MethodCallExpression;
if(callExpression == null)
{
throw new Exception("expression must be a MethodCallExpression");
}
return callExpression.Method.Name;
}
}
在此实现任何意见?
这篇关于从LINQ表达式提取方法名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!