一段实例代码, 在 c#中通过 Linq 取变量的名称, 以及 将字符串转为变量名,通过字符串给变量赋值.
string strApp = "app";
public string app = "AAA";
public string strTest = "TEST";
protected void Button1_Click(object sender, EventArgs e)
{
//通过字符串获得变量值
string aaa1 = this.GetType().GetField("app").GetValue(this).ToString();
//或者
string aaa2 = this.GetType().GetField(strApp).GetValue(this).ToString();
//通过给变量赋值
this.GetType().GetField("strTest").SetValue(this, "C#123");
//新的值
string bbb = this.GetType().GetField("strTest").GetValue(this).ToString();
//获取变量名称
string ccc = GetVarName(p=>this.strTest);
}
//获取变量名称
public static string GetVarName(System.Linq.Expressions.Expression<Func<string, string>> exp)
{
return ((System.Linq.Expressions.MemberExpression)exp.Body).Member.Name;
}



