找了好久,最后在国外的论坛找到了解决办法,直接贴代码吧。
方法一:
public static class MemberInfoGetting
{
public static string GetMemberName<T>(Expression<Func<T>> memberExpression)
{
MemberExpression expressionBody = (MemberExpression)memberExpression.Body;
return expressionBody.Member.Name;
}
} string TableName = "";
string nameOfTestVariable = MemberInfoGetting.GetMemberName(() => TableName); //最后得到 nameOfTestVariable = "TableName"
方法二:
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()[].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(), )).Name;
}