2013-04-20 56 views
-1

我正在編寫一個簡單的水果機器,這是我的一種方法,我想知道是否有可能使此代碼更有效:(在使用case之前它有一個if/else if語句)c#如何使此代碼比案例更有效

_intNudgeCount得到一個介於0 - 9之間的數字,因此是這種情況。

public void DrawNudgeCount() 
    { 
     switch (_intNudgeCount) 
     { 
      case 9: 
       pictureBoxNudgeCount.Image = Properties.Resources._9; 
       break; 
      case 8: 
       pictureBoxNudgeCount.Image = Properties.Resources._8; 
       break; 
      case 7: 
       pictureBoxNudgeCount.Image = Properties.Resources._7; 
       break; 
      case 6: 
       pictureBoxNudgeCount.Image = Properties.Resources._6; 
       break; 
      case 5: 
       pictureBoxNudgeCount.Image = Properties.Resources._5; 
       break; 
      case 4: 
       pictureBoxNudgeCount.Image = Properties.Resources._4; 
       break; 
      case 3: 
       pictureBoxNudgeCount.Image = Properties.Resources._3; 
       break; 
      case 2: 
       pictureBoxNudgeCount.Image = Properties.Resources._2; 
       break; 
      case 1: 
       pictureBoxNudgeCount.Image = Properties.Resources._1; 
       break; 
      case 0: 
       pictureBoxNudgeCount.Image = Properties.Resources._0; 
       break; 
     } 
    } 

在此先感謝!

解決:

沒事的,我知道了下降到3行代碼:

//在類的頂部聲明資源的圖像。

private System.Drawing.Image[] _arrayNudgeCount; 

//在加載類時填充數組。

_arrayNudgeCount = new System.Drawing.Image[] { Properties.Resources._0, Properties.Resources._1}; 

//重繪圖像

public void DrawNudgeCount() 
{ 
pictureBoxNudgeCount.Image = _arrayNudgeCount[_intNudgeCount]; 
} 
+0

我建議你看看一個這個帖子:http://stackoverflow.com/questions/767821/is-else-if-faster-than-switch-case – 2013-04-20 19:37:22

+0

我以前做過類似的東西,我試圖減少我有的代碼行數量,或者這是做這件事的最有效的方式? – user2302941 2013-04-20 19:40:30

+0

@ user2302941刪除問題或添加解決方案並接受它。 – Yatrix 2013-04-20 20:04:06

回答

0

我會把它減少到只有一行代碼我是你!

pictureBoxNudgeCount.Image = (Image)Properties.Resources.ResourceManager.GetObject("_" + _intNudgeCount); 
0

您的圖像放在一個文件夾中appilication的旁邊,叫pictureBoxNudgeCount.Load(ConstantSectionPath + _intNudgeCount + 「JPG」);如果jpg是你的文件擴展名。