认为我有一个如下课程:
public class Foo
{
public int Bar { get; set; }
public int Sum(int a, int b)
{
return a + b;
}
public int Square(int a)
{
return a * a;
}
}
所有你知道我可以编写一个返回给定属性名称的方法:
var name = GetPropertyName<Foo>(f => f.Bar); //returns "Bar"
GetPropertyName方法可以轻松实现,如下所示:
public static string GetPropertyName<T>(Expression<Func<T, object>> exp)
{
var body = exp.Body as MemberExpression;
if (body == null)
{
var ubody = (UnaryExpression)exp.Body;
body = ubody.Operand as MemberExpression;
}
return body.Member.Name;
}
但我想像下面的属性名一样轻松获取方法名称:
var name1 = GetMethodName<Foo>(f => f.Sum); //expected to return "Sum"
var name2 = GetMethodName<Foo>(f => f.Square); //expected to return "Square"
是否可以编写这样的GetMethodName方法?
请注意:GetMethodName必须独立于给定方法的签名或返回值。
答案 0 :(得分:7)
经过一些研究,我发现Expression<Action<T>>
应足以做你想做的事。
private string GetMethodName<T>(Expression<Action<T>> method)
{
return ((MethodCallExpression)method.Body).Method.Name;
}
public void TestMethod()
{
Foo foo = new Foo();
Console.WriteLine(GetMethodName<Foo>(x => foo.Square(1)));
Console.WriteLine(GetMethodName<Foo>(x => foo.Sum(1,1)));
Console.ReadLine();
}
public class Foo
{
public int Bar { get; set; }
public int Sum(int a, int b)
{
return a + b;
}
public int Square(int a)
{
return a * a;
}
}