I have class Test:
class Test
{
public int Id {get;set;}
public string Name {get;set;}
}
And function Exec which accepts expression:
void Exec<T>(Expression<Func<T, object>> expression)
{
}
...
Exec<Test>(t => t.Id);
How can I get the property name used in expression? In the code above this should be 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);
// ...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With