例子一、将字符串转为变量名
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());
}
例子二、通过字符串给变量赋值
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, "gisoracle@126.com");
//新的值
MessageBox.Show(this.GetType().GetField("gisoracle").GetValue(this).ToString());
}
本文提供了两个C#编程示例,演示如何利用反射机制实现通过字符串获取并操作变量值。第一个示例展示了如何将字符串转换为变量名,并读取其值;第二个示例则进一步说明了如何通过字符串给变量赋新值。
1万+

被折叠的 条评论
为什么被折叠?



