2016-09-25 78 views
1

我該怎麼寫這個更短?對於每種情況,我必須寫這個,然後它太長,因爲有48個數字,所以我需要48個案例。有沒有辦法讓循環?如何使循環代替switch語句?

switch (ballBounce.ToString()) 
     { 
      case "1": 
       if (ballBounce == n0) 
       { 
        textBox1.Text = number.ToString();       
       } 
       break; 

      case "2": 
       if (ballBounce == n1) 
       { 
        textBox1.Text = number.ToString(); 
       } 
       break; 

      case "3": 
       if (ballBounce == n2) 
       { 
        textBox1.Text = number.ToString(); 
       } 
       break; ... 
+0

你顯然採取了錯誤的方式。但是你的代碼太短,無法理解它的功能。但是從那我可以說n0,n1,n2應該是一個數組。 – bokan

+0

你只需要將'ballBounce'與'nX'配對。聽起來像你需要一個'字典',然後簡單地說:'if(ballBounce == dictionary [ballBounce])textBox1.Text = number.ToString()' – haim770

回答

4

在這種情況下,循環無用。 您可以使用字典。

private Dictinoary<string, string> cases = new Dictionary<string, string> { 
    {"1", "one"}, 
    {"2", "two"}, 
    // ... 
}; 

// in some method 
string text; 
if (cases.TryGetValue(ballBounce.ToString(), out text)){ 
    this.textBox1.Text = text; 
} 

如果你想要比簡單的值更聰明的東西,你可以在字典中有功能。

private Dictinoary<string, Func<string>> cases = new Dictionary<string, Func<string>> { 
    {"1",() => "one"}, 
    {"2",() => 
    { 
     if (DateTime.Now.Seconds % 2 == 0) { return "A"; } 
     else { return "B"; } 
    }}, 
    // ... 
}; 

// in some method 
Func<string> textProvider; 
if (cases.TryGetValue(ballBounce.ToString(), out textProvider)){ 
    this.textBox1.Text = textProvider(); 
} 
0

爲什麼使用ifcase? 你不需要檢查兩次。 此外,如果這是對每一個案件

textBox1.Text = number.ToString(); 

的代碼,那麼你不需要switchif 僅僅指剛寫textBox1.Text = number.ToString();,你是好去。 此外,如果你有一些情況下,ONY,你可以這樣做的:

switch (ballBounce.ToString()) 
{ 
    case "1": 
    case "2": 
    case"3": 
    //.... 
    textBox1.Text = number.ToString(); 
} 
1

根據您的ToString()的,我假設ballBounce是一個int。

if (ballBounce <= 48 && ballBounce > 0) 
{ 
    textBox1.Text = ballBounce.ToString(); 
}