0
在下面的示例中,是否可以使用kvp.value指向全局变量(num1,num2,num3)?C#使用字符串值作为整数的名称
int num1;
int num2;
int num3;
private void button1_Click(object sender, EventArgs e)
{
List<KeyValuePair<TextBox, string>> myList = new List<KeyValuePair<TextBox, string>>();
myList.Add(new KeyValuePair<TextBox, string>(textBox1, "num1"));
myList.Add(new KeyValuePair<TextBox, string>(textBox2, "num2"));
myList.Add(new KeyValuePair<TextBox, string>(textBox3, "num3"));
foreach (KeyValuePair<TextBox, string> kvp in myList)
{
TextBox tb= kvp.Key;
try
{
num1 = int.Parse(tb.Text);
//instead of using the hardcoded variable name num1 i want to use kvp.value
//kvp.value = int.Parse(tb.Text);
}
catch
{
//blah blah
}
}
}
我删除了我以前的文章,因为它很不清楚,希望这会好一点。
HTTP:// WWW .dotnetperls.com/reflection-field我认为这是你想要的 – user2167382 2014-12-07 14:09:36
你需要在代码中的其他地方使用变量num1,num2,num3吗? – 2014-12-07 14:10:04
是的,他们用在其他地方 – Osprey231 2014-12-07 14:11:34