/// <summary>
/// 获取表达式调用的字段名称
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="expr"></param>
/// <returns></returns>
private string GetPropertyName<T>(Expression<Func<T, object>> expr)
{
switch (expr.Body)
{
case MemberExpression memberExpression:
return memberExpression.Member.Name;
case UnaryExpression unaryExpression:
if (unaryExpression.Operand is MemberExpression expression)
{
return expression.Member.Name;
}
break;
default:
break;
}
return "";
}
调用方法
string desc = GetPropertyName<A>(f => f.Id);
System.Console.WriteLine(desc);