找了好久,最后在国外的论坛找到了解决办法,直接贴代码吧。
方法一:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
public static class MemberInfoGetting { public static string GetMemberName<T>(Expression<Func<T>> memberExpression) { MemberExpression expressionBody = (MemberExpression)memberExpression.Body; return expressionBody.Member.Name; } } string TableName = "123"; string nameOfTestVariable = MemberInfoGetting.GetMemberName(() => TableName); //最后得到 nameOfTestVariable = "TableName" |
方法二:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
static void Main(string[] args) { GetName(new { var1 }); GetName2(() => var1); GetName3(() => var1); } static string GetName<T>(T item) where T : class { return typeof(T).GetProperties()[0].Name; } static string GetName2<T>(Expression<Func<T>> expr) { return ((MemberExpression)expr.Body).Member.Name; } static string GetName3<T>(Func<T> expr) { return expr.Target.GetType().Module.ResolveField(BitConverter.ToInt32(expr.Method.GetMethodBody().GetILAsByteArray(), 2)).Name; } |