【发布时间】:2013-09-14 09:20:59
【问题描述】:
认为我有一个像下面这样的课程:
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 必须独立于给定方法的签名或返回值。
【问题讨论】:
-
您是否有机会事先知道方法
f.Sum,但仍想在另一个方法中传递它,只返回字符串"Sum"?这根本没有意义。 -
用
Foo.Sum代替f => f.Sum -
@leppie 它的签名与
Func<T, object>不兼容 -
@IlyaIvanov:所以重载
GetMethodName(对于所有变化;p)
标签: c# reflection lambda