我知道可以检索具有返回类型的属性名称或方法。但是是否也可以通过 LINQ 表达式树获得没有返回类型的方法名称?
示例:字符串方法名 = GetMethodname(x=>x.GetUser());
---> 结果:“GetUser”
最佳答案
当然 - 但您需要这样的方法签名:
public static string GetMethodName<T>(Expression<Action<T>> action)
(这意味着您需要在调用它时指定类型参数,以便使用 lambda 表达式。)
示例代码:
using System;
using System.Linq.Expressions;
class Test
{
void Foo()
{
}
static void Main()
{
string method = GetMethodName<Test>(x => x.Foo());
Console.WriteLine(method);
}
static string GetMethodName<T>(Expression<Action<T>> action)
{
MethodCallExpression methodCall = action.Body as MethodCallExpression;
if (methodCall == null)
{
throw new ArgumentException("Only method calls are supported");
}
return methodCall.Method.Name;
}
}
关于LINQ 是否可以通过 LINQ 表达式树获取没有返回类型的方法名称?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1524290/