在此表单中组合foreach按钮和标签

时间:2018-03-27 15:04:30

标签: c#

我很好奇我是否可以将这两个代码合并为一个

foreach (Control c in this.Controls)
{
    if (c is Button)
    {
    }

foreach (Control f in this.Controls)
{
    if (f is Label)
    {
    }
}

有什么方法可以混合它们吗?

1 个答案:

答案 0 :(得分:1)

您可以删除第二个foreach并使用else if

foreach (Control c in this.Controls)
{
    if (c is Button)
    {
        Button button = c as Button;
        // Do something with 'button' here
    }
    else if (c is Label)
    {
        Label label = c as Label;
        // Do something with 'label' here
    }
}

或者,如果您想要控件是Button a Label,您可以使用OR运算符:

foreach (Control c in this.Controls)
{
    if (c is Button || c is Label)
    {
        // Do something here
        c.Tag = "I'm a button or a label";
    }
}