C#变量名转换成字符串以及字符串转为变量名

在c#中把字符串转为变量名并获取变量值的小例子(转)
public class Program

{

public string str = "spp";

public string spp = "Hello World!";

public static void Main(string[] args)

{

Program p = new Program();

Console.WriteLine(p.GetType().GetField(p.str).GetValue(p).ToString());

Console.ReadKey();

}

}
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> exp)
        {
            return ((System.Linq.Expressions.MemberExpression)exp.Body).Member.Name;
        }

 

你可能感兴趣的:(总栏目)