Lambda获取类属性的名字
using System;
using System.ComponentModel;
using System.Linq.Expressions;
using System.Reflection;
public static class ClassExt { private static MemberInfo GetMemberInfo(Expression expression) { LambdaExpression lambdaExpression = (LambdaExpression)expression; MemberExpression memberExpression = (!(lambdaExpression.Body is UnaryExpression)) ? ((MemberExpression)lambdaExpression.Body) : ((MemberExpression)((UnaryExpression)lambdaExpression.Body).Operand); return memberExpression.Member; } public static string PropName<TProperty>(this object obj, Expression<Func<TProperty>> property) { return GetMemberInfo(property).Name; } } class A { public int Prop { get; set; } private void Example() { string propName = this.PropName(() => Prop); Console.WriteLine(propName); //Prop } }
转载保留源出处即可,商业使用请自行鉴别,使用本博客中公开内容做任何违法犯罪于本作者无关