c# 获取变量名

也不知道哪里需要用到。反正很多人问。

这里就贴一下方法,也是忘记从哪里看到的了,反正是转载的!


public static void Main(string[] args)
        {
            string abc="123";
            //调用
            string result = GetVarName(p => abc);
            Console.WriteLine(result);

            Console.ReadLine();
        }

        //获取方法
        public static string GetVarName(System.Linq.Expressions.Expression<Func<string, string>> exp)
        {
            return ((System.Linq.Expressions.MemberExpression)exp.Body).Member.Name;
        }


C#6.0可以直接使用 

string abc = "123";
            Console.WriteLine(nameof(abc));


原文地址:https://www.cnblogs.com/hanjun0612/p/9779867.html