我有类测试:
class Test
{
public int Id {get;set;}
public string Name {get;set;}
}
以及接受表达式的函数 Exec:
void Exec<T>(Expression<Func<T, object>> expression)
{
}
...
Exec<Test>(t => t.Id);
如何获取表达式中使用的属性名称?在上面的代码中,这应该是 Id。
Something like:
private static string GetMemberName(Expression expression)
{
switch(expression.NodeType)
{
case ExpressionType.MemberAccess:
return ((MemberExpression)expression).Member.Name;
case ExpressionType.Convert:
return GetMemberName(((UnaryExpression)expression).Operand);
default:
throw new NotSupportedException(expression.NodeType.ToString());
}
}
with:
public void Exec<T>(Expression<Func<T, object>> expression)
{
string name = GetMemberName(expression.Body);
// ...
}