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