C#使用字符串值作为整数的名称

时间:2014-12-07 14:01:40

标签: c#

在下面的示例中,是否可以使用kvp.value指向全局变量(num1,num2,num3)?

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
              }

          }

}

我删除了之前的帖子,因为它非常不清楚,希望这有点好。

1 个答案:

答案 0 :(得分:1)

通过引入包装类,可以更容易地将全局变量(从int)更改为引用类型:

class Number<T>
{
    public Number(T value)
    {
        Value = value;
    }

    public T Value { get; set; }
}

您的代码将是:

Number<int> num1 = new Number<int>(0);
Number<int> num2 = new Number<int>(0);
Number<int> num3 = new Number<int>(0);



private void button1_Click(object sender, EventArgs e)
{
    List<KeyValuePair<TextBox, Number<int>>> myList = new List<KeyValuePair<TextBox, Number<int>>>();
    myList.Add(new KeyValuePair<TextBox, Number<int>>(textBox1, num1));
    myList.Add(new KeyValuePair<TextBox, Number<int>>(textBox2, num2));
    myList.Add(new KeyValuePair<TextBox, Number<int>>(textBox3, num3));

    foreach (KeyValuePair<TextBox, Number<int>> kvp in myList)
    {
        TextBox tb = kvp.Key;
        try
        {
            kvp.Value.Value = 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
        }

    }

}