方法一:

  1. public static class MemberInfoGetting
  2. {
  3. public static string GetMemberName<T>(Expression<Func<T>> memberExpression)
  4. {
  5. MemberExpression expressionBody = (MemberExpression)memberExpression.Body;
  6. return expressionBody.Member.Name;
  7. }
  8. }
  9. string TableName = "123";
  10. string nameOfTestVariable = MemberInfoGetting.GetMemberName(() => TableName);
  11. //最后得到 nameOfTestVariable = "TableName"

方法二:

  1. static void Main(string[] args)
  2. {
  3. GetName(new { var1 });
  4. GetName2(() => var1);
  5. GetName3(() => var1);
  6. }
  7. static string GetName<T>(T item) where T : class
  8. {
  9. return typeof(T).GetProperties()[0].Name;
  10. }
  11. static string GetName2<T>(Expression<Func<T>> expr)
  12. {
  13. return ((MemberExpression)expr.Body).Member.Name;
  14. }
  15. static string GetName3<T>(Func<T> expr)
  16. {
  17. return expr.Target.GetType().Module.ResolveField(BitConverter.ToInt32(expr.Method.GetMethodBody().GetILAsByteArray(), 2)).Name;
  18. }

作者:黄聪
出处:http://www.cnblogs.com/huangcong/