LINQ Casting问题

Abr*_*mJP 2 c# linq

我有一个winform,有两个复选框和一个按钮.在两个复选框的CheckedChanged事件中,我给出了以下代码.

//Enable the button if any of the checkbox is checked
var ChkBoxes = from CheckBox ctrl in this.Controls 
               where ctrl is CheckBox select ctrl;
button1.Enabled = ChkBoxes.Any(c => ((CheckBox)c).Checked);
Run Code Online (Sandbox Code Playgroud)

但是当检查其中任何一个复选框时,我收到错误" 无法将类型'System.Windows.Forms.Button'的对象强制转换为'System.Windows.Forms.CheckBox'. "执行第二行时出现错误代码

后来我将代码更新为以下版本,工作正常.我做的唯一改变是从CheckBoxControl的修改ctrl类型.

var ChkBoxes = from Control ctrl in this.Controls 
               where ctrl is CheckBox select ctrl;
button1.Enabled = ChkBoxes.Any(c => ((CheckBox)c).Checked);
Run Code Online (Sandbox Code Playgroud)

我的问题是,在这两种情况下我只返回类型复选框的控件,然后如何出现转换错误.有谁能解释我这是如何工作的?

Ree*_*sey 6

而不是使用:

var ChkBoxes = from CheckBox ctrl in this.Controls where ctrl is CheckBox select ctrl;
Run Code Online (Sandbox Code Playgroud)

尝试使用Enumerable.OfType<T>过滤:

var chkBoxes = this.Controls.OfType<CheckBox>();
button1.Enabled = chkBoxes.Any(c => c.Checked); // No cast required now
Run Code Online (Sandbox Code Playgroud)