字符串轉組件名
(Controls["button1"] as Button).Text = "Hello";//單獨組件 (Controls["tabControl1"].Controls[0].Controls["DataSource1"] as TextBox).Text = "111.111.111.111";//嵌套組件
字符串轉變量名
string str = "demo"; //可以寫到下面button1_Click裡面,demo就是下面的變量名
public string demo = "Old String";
private void button1_Click(object sender, EventArgs e)
{
//通過字符串獲得變量值
MessageBox.Show(this.GetType().GetField(str).GetValue(this).ToString()); //顯示Old String
GetType().GetField(str).SetValue(this, "New String");
MessageBox.Show(spp); //顯示New String
MessageBox.Show(this.GetType().GetField(str).GetValue(this).ToString()); //顯示New String
}
或
public string Demo = "Old String";
private void button2_Click(object sender, EventArgs e)
{
//通過字符串獲得變量值
MessageBox.Show(this.GetType().GetField("Demo").GetValue(this).ToString()); //顯示Old String
//通過給變量賦值
this.GetType().GetField("Demo").SetValue(this, "New String");
//新的值
MessageBox.Show(Demo); //顯示New String
MessageBox.Show(this.GetType().GetField("Demo").GetValue(this).ToString()); //顯示New String
}