找到多种类型的所有控件?

use*_*400 2 c# ienumerable winforms

我试图在 C# 程序中查找单选按钮或复选框的所有控件。另外,我还想找到某个文本框。我只让它与单选按钮一起工作 - 如果我用复选框重复 IEnumerable 行,它会告诉我已经在此范围内定义了一个名为 Button 的局部变量。谢谢您的帮助。

IEnumerable<RadioButton> buttons = this.Controls.OfType<RadioButton>();

foreach (var Button in buttons)
{
    //Do something
}
Run Code Online (Sandbox Code Playgroud)

its*_*e86 7

您可以通过使用公共基类来完成您想要做的事情Control

IEnumerable<Control> controls = this.Controls
    .Cast<Control>()
    .Where(c => c is RadioButton || c is CheckBox || (c is TextBox && c.Name == "txtFoo"));

foreach (Control control in controls)
{
    if (control is CheckBox)
        // Do checkbox stuff
    else if (control is RadioButton)
        // DO radiobutton stuff
    else if (control is TextBox)
        // Do textbox stuff
}
Run Code Online (Sandbox Code Playgroud)