委托替换重复代码[英] Delegate to replace repeating code

本文是小编为大家收集整理的关于委托替换重复代码的处理方法,想解了委托替换重复代码的问题怎么解决?委托替换重复代码问题的解决办法?委托替换重复代码问题的解决方案?那么可以参考本文帮助大家快速定位并解决问题,译文如有不准确的地方,大家可以切到English参考源文内容。

问题描述

我在一个组框中有10个复选框.最高的复选框标记为" ALL"检查其他9个复选框,当检查时为" ALL"

在其他9个复选框中,我的代码基本相同.这是两个复选框的示例:

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;
    }

我讨厌重复相同的代码.我将如何创建一个仅使用一个事件方法来完成以上内容的代表?

推荐答案

您可以将单个Click用于所有复选框的事件处理程序.筹集了事件的实际复选框将从sender参数可用.只需将其施放到复选框类型:

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

您也无需将布尔值与True/false比较布尔值 - 您可以直接在if语句中使用它们.

btw 您还应该在检查所有复选框时验证情况,并在这种情况下设置ckAll.Checked = true.

其他推荐答案

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

本文地址:https://www.itbaoku.cn/post/510088.html

问题描述

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?

推荐答案

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.

其他推荐答案

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