在MSDN论坛看到有人问:C#里面中将字符串转为变量名
例如:
string str = "spp";
string spp = "very good";
怎样搞 str 而得到 very good 这个值?
string str = "spp";
string spp = "very good";
怎样搞 str 而得到 very good 这个值?
答案:
public partial class Form1 : Form
{
string str = "spp";
public string spp = "very good";
public Form1()
{
InitializeComponent();
MessageBox.Show(this.GetType().GetField(str).GetValue(this).ToString());
}
}
{
string str = "spp";
public string spp = "very good";
public Form1()
{
InitializeComponent();
MessageBox.Show(this.GetType().GetField(str).GetValue(this).ToString());
}
}
其实平时这样用到很少,但是这个问题至少可以巩固下基础知识和一点小技巧
转载于:https://blog.51cto.com/tobetobe/287804