我很好奇我是否可以将这两个代码合并为一个
foreach (Control c in this.Controls)
{
if (c is Button)
{
}
foreach (Control f in this.Controls)
{
if (f is Label)
{
}
}
有什么方法可以混合它们吗?
答案 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";
}
}