2014-12-07 59 views
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 
       } 

      } 

} 

我刪除了我以前的文章,因爲它很不清楚,希望這會好一點。

+0

HTTP:// WWW .dotnetperls.com/reflection-field我認爲這是你想要的 – user2167382 2014-12-07 14:09:36

+0

你需要在代碼中的其他地方使用變量num1,num2,num3嗎? – 2014-12-07 14:10:04

+0

是的,他們用在其他地方 – Osprey231 2014-12-07 14:11:34

回答

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 
     } 

    } 

} 
+0

這工程是一種享受!非常感謝 :) – Osprey231 2014-12-07 15:10:10