例子一、將字符串轉為變量名
string str = "spp";
public string spp = "very good";
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(this.GetType().GetField(str).GetValue(this).ToString());
}
來自:http://social.microsoft.com/Forums/zh-CN/visualcshartzhchs/thread/3b7c7d4d-925b-4d72-bee0-6c39c2e2786b
例子二、通過字符串給變量賦值
public string gisoracle = "ok";
private void button2_Click(object sender, EventArgs e)
{
//通過字符串獲得變量值
MessageBox.Show(this.GetType().GetField("gisoracle").GetValue(this).ToString());
//通過給變量賦值
this.GetType().GetField("gisoracle").SetValue(this, "[email protected]");
//新的值
MessageBox.Show(this.GetType().GetField("gisoracle").GetValue(this).ToString());
}