C# 字符串转组件名、变量名

字符串转组件名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
}
相关文章
相关标签/搜索