Roo*_*ian 3 linq tree expression get properties
我知道可以检索属性名称或返回类型的方法.但是也可以通过LINQ表达式树获得没有返回类型的方法名称吗?
示例:string methodname = GetMethodname(x => x.GetUser());
--->结果:"GetUser"
绝对 - 但你需要一个像这样的方法签名:
public static string GetMethodName<T>(Expression<Action<T>> action)
Run Code Online (Sandbox Code Playgroud)
(这意味着你需要在调用时指定type参数,以便使用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;
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
959 次 |
最近记录: |