字符串轉組件名this
(Controls["button1"] as Button).Text = "Hello";//單獨組件 (Controls["tabControl1"].Controls[0].Controls["DataSource1"] as TextBox).Text = "111.111.111.111";//嵌套組件
字符串轉變量名spa
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 }
或code
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 }