[英]How can i optimize this code?
我有以下代碼:
if (userValueSom01 == realResult01)
{
//answer = correct
//count +1 for overall good answers
WpfApplication1.Properties.Settings.Default.totallGood++;
//count for good +1
answerThisWindowGood++;
//make visible the green logo
Som01G.Visibility = Visibility.Visible;
}
else
{
//answer = wrong
//count +1 for overall wrong answers
WpfApplication1.Properties.Settings.Default.totallWrong++;
//count for wrong +1
answerThisWindowWrong++;
//make visible the red logo
Som01W.Visibility = Visibility.Visible;
labelSom01Check.Content = Convert.ToString(realResult01);
}
現在的關鍵是,這發生了XX次,其中XX是一個與您在代碼中看到的數字相對應的數字。 因此,在上面的示例中,XX是01。*請注意,其輸入中也包含01,結果中也包含01。
在不很深入的C#中(還),起初我以為XX為20時,我需要將此部分復制20次以上,並更改數字。 現在這看起來很麻煩,我想應該有一些更聰明的方法來處理這個問題,重點是,我想不起來(如上所述,我對C#的了解還不是很深)。
有人可以將我推向正確的方向嗎?
先感謝您。
---編輯1 ---謝謝Miika L.與您的解決方案略有不同:
public bool checkValue(double value, int result, Image controlG, Image controlW, Label label)
{
if (value == result)
{
//... Do stuff
controlG.Visibility = Visibility.Visible;
return true;
}
else
{
//... Do other stuff
controlW.Visibility = Visibility.Visible;
label.Content = result.ToString();
return false;
}
}
現在我確實可以調用:bool test = checkValue(userValueSom01,realResult01,Som01G,Som01W,labelSom01Check);
作品:) thanx!
將其編寫為函數呢?
public bool checkValue(
int value,
int result,
Control controlG,
Control controlW,
Label label)
{
if (value == result)
{
... Do stuff
controlG.Visibility = Visibility.Visible;
}
else
{
... Do other stuff
controlW.Visibility = Visibility.Visible;
label.Content = result.ToString();
}
}
與其使用userValueSom01之類的名稱來定義數以百計的變量,realResult01最好使用適當的數組或字典 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.