从任意地方获取某一个类中某一个属性的字符串名称。
比如
public class SomeThing { public string JustTest { get; set; } }
想要通过new SomeThing.JustTest返回"JustTest"
public static string GetMemberName(LambdaExpression lambda) { var member = lambda.Body as MemberExpression; if (member == null) throw new NotSupportedException( "The final part of the lambda is not a member-expression"); return member.Member.Name; }
使用方式
Expression<Func<object>> expr = () => new SomeThing().JustTest; Console.WriteLine("This is "+Utils.GetMemberName(expr));
结果:This is JustTest