使用相同代码的真假条件

时间:2018-10-19 21:54:37

标签: c#

我有一个简单的CheckedChange事件,该事件会选中该复选框,或者是否选中了一个复选框则将其取消选中:

private void chkAll_CheckedChanged(object sender, EventArgs e)
        {
            if (chkAll.Checked)
            {
                chkByName.Checked = true;
                chkByDesign.Checked = true;
                chkByAddress.Checked = true;
                chkByCity.Checked = true;
                chkByZip.Checked = true;
                chkByContact.Checked = true;
                chkByCustomer.Checked = true;
                chkByJobNote.Checked = true;
            }
            else
            {
                chkByName.Checked = false;
                chkByDesign.Checked = false;
                chkByAddress.Checked = false;
                chkByCity.Checked = false;
                chkByZip.Checked = false;
                chkByContact.Checked = false;
                chkByCustomer.Checked = false;
                chkByJobNote.Checked = false;
            }

如您所见,我有很多重复的代码。我只是改变对还是错。有没有办法减少代码?还有另一种最佳做法吗?

3 个答案:

答案 0 :(得分:2)

另一种选择是将必须设置的所有复选框添加到创建表单时初始化的集合中。

然后简单地遍历它并相应地设置checked属性;

//while initializing
chkCollection.Add(chkByName);
chkCollection.Add(chkByDesing);
...

private void chkAll_CheckedChanged(
    object sender, EventArgs e)
{
    foreach (var chk in chkCollection)
        chk.Checked = checkAll.Checked;
}

如果必须设置表单中的所有复选框,则可以简单地过滤myForm.Controls并避免创建特定的集合。

答案 1 :(得分:1)

您可以将Checked属性直接设置为chkAll.Checked

chkByName.Checked = chkAll.Checked
chkByDesign.Checked = chkAll.Checked;
chkByAddress.Checked = chkAll.Checked;
chkByCity.Checked = chkAll.Checked;
chkByZip.Checked = chkAll.Checked;
chkByContact.Checked = chkAll.Checked;
chkByCustomer.Checked = chkAll.Checked;
chkByJobNote.Checked = chkAll.Checked;

答案 2 :(得分:1)

在C#中,赋值可以用作产生赋值本身的表达式:

chkByName.Checked =
chkByDesign.Checked =
chkByAddress.Checked =
chkByCity.Checked =
chkByZip.Checked =
chkByContact.Checked =
chkByCustomer.Checked =
chkByJobNote.Checked = chkAll.Checked;

即在

x = a = b;

a = b产生b。因此,上面的表达式等效于:

x = (a = b);

x = a = b = c;

等同于

x = (a = (b = c));