Delegate to replace repeating code

匆匆过客 提交于 2019-12-13 06:09:37

问题


I have 10 check boxes in a group box. The top check box labeled "All" checks the other 9 check boxes when checked is true for "All"

In the other 9 checkboxes, I have essentially the same code. Here is a sample for two of the check boxes:

private void ckDal_Click(object sender, EventArgs e)
    {
        if (ckDal.Checked == false)
            ckAll.Checked = false;
    }

    private void ckHou_Click(object sender, EventArgs e)
    {
        if (ckHou.Checked == false)
            ckAll.Checked = false;
    }

I hate repeating the same code. How would I create a delegate to accomplish the above with just one event method?


回答1:


You can use single Click event handler for all CheckBoxes. Actual CheckBox, which raised the event, will be available from sender parameter. Just cast it to CheckBox type:

private void ck_Click(object sender, EventArgs e)
{
    if (!((CheckBox)sender).Checked)
        ckAll.Checked = false;
}

Also you don't need to compare boolean values with true/false - you can use them directly in if statement.

BTW you should also verify case when all CheckBoxes were checked, and set ckAll.Checked = true in that case.




回答2:


private void CheckBoxClick(object sender, EventArgs e)
{        
    if (!((CheckBox)sender).Checked)
        ckAll.Checked = false;
}


来源:https://stackoverflow.com/questions/14031490/delegate-to-replace-repeating-code

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!