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

查看:85
本文介绍了代理替换重复代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个组框中有10个复选框。标记为全部的顶部复选框在选中全部时检查其他9个复选框。

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"

在其他9个复选框中,我基本上都是相同的代码。下面是两个复选框的示例:

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?

推荐答案

您可以使用单个单击所有复选框的事件处理程序。引发事件的实际CheckBox将从 sender 参数中获取。只需将其转换为CheckBox类型:

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

此外,您不需要将布尔值与true / false进行比较可以直接在 if 语句中使用它们。

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

在这种情况下,所有复选框都被检查,并设置 ckAll.Checked = true

这篇关于代理替换重复代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆