[英]“if” that doesn't work perfectly
此代碼有什么問題? combobox
都是"Wholesale"
或"Retail"
形式,顯示第二個語句(true,true)。 如果我取消checkbox
該checkbox
則else
可以工作( true
, false
)。 知道為什么嗎?
private void checkBox3_CheckedChanged(object sender, EventArgs e)
{
if (checkBox3.Checked == true || comboBox1.SelectedText == "Standalone")
{
this.checkBox1.BackColor = Color.Gray;
this.checkBox1.Enabled = false;
this.checkBox2.BackColor = Color.Gray;
this.checkBox2.Enabled = false;
}
if (checkBox3.Checked == true || comboBox1.SelectedText == "Retail")
{
this.checkBox1.BackColor = default(Color);
this.checkBox1.Enabled = true;
this.checkBox2.BackColor = default(Color);
this.checkBox2.Enabled = true;
}
else
{
this.checkBox1.BackColor = default(Color);
this.checkBox1.Enabled = true;
this.checkBox2.BackColor = Color.Gray
this.checkBox2.Enabled = false;
}
一個簡單的else if
和&&
的用法應該可以解決問題:
if (checkBox3.Checked == true && comboBox1.SelectedText == "Standalone")
{
...
//If this case is true, the following cases are not going to be checked
}
else if (checkBox3.Checked == true && comboBox1.SelectedText == "Retail")
{
...
//If this case is true, the following cases are not going to be checked
}
else
{
...
//No case before was true
}
需要注意的是一個簡單的使用if
后面的if
是不一樣的用法else if
在后面if
。
還要注意,僅在第三個CheckBox
的狀態更改后才調用方法checkBox3_CheckedChanged
(除非您為其他事件使用了該方法)
我建議if
此處消除所有內容,並且僅使用布爾公式進行運算 。 首先,讓我們擺脫討厭的問題(checkBox3.Checked == true || comboBox1.SelectedText == "Standalone")
:
bool isRetail = checkBox3.Checked && comboBox1.SelectedText == "Retail";
bool isStandalone = checkBox3.Checked && comboBox1.SelectedText == "Standalone";
然后嘗試猜測何時應該Enabled
CheckBox
:
// checkBox2 is enabled if and only if isRetail
//TODO: can see, how checkBox2 is unreadable? Change the name into, say "boxIsRetail"
this.checkBox2.Enabled = isRetail;
// checkBox2 is enabled if and only if neither isRetail nor isStandalone
//TODO: can see, how checkBox1 is unreadable? Change the name into, say "boxIsNeither"
this.checkBox1.Enabled = !(isRetail || isStandalone);
最后,我們應該更新其Color
。 CheckBox
的Color
僅取決於Enabled
:
this.checkBox1.BackColor = this.checkBox1.Enabled ? default(Color) : Color.Gray;
this.checkBox2.BackColor = this.checkBox2.Enabled ? default(Color) : Color.Gray;
放在一起,我們有
private void checkBox3_CheckedChanged(object sender, EventArgs e) {
bool isRetail = checkBox3.Checked && comboBox1.SelectedText == "Retail";
bool isStandalone = checkBox3.Checked && comboBox1.SelectedText == "Standalone";
checkBox2.Enabled = isRetail;
checkBox1.Enabled = !(isRetail || isStandalone);
//TODO: these lines are good candidate to be extracted into a method "UpdateColor"
checkBox1.BackColor = checkBox1.Enabled ? default(Color) : Color.Gray;
checkBox2.BackColor = checkBox2.Enabled ? default(Color) : Color.Gray;
}
請注意,您可以輕松添加另一個bool
變量,例如isWholesale
, isReserved
等,並實現相應的邏輯,而無需在if
, else
和if else
樹中漫游
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.