想不出更好的标题,所以很抱歉..
我正在尝试转换 this method ,它将检索表单的所有子控件,作为扩展方法并接受接口(interface)作为输入。到目前为止,我正在做
public IEnumerable<Control> GetAll<T>(this Control control) where T : class
{
var controls = control.Controls.Cast<Control>();
return controls.SelectMany(ctrl => GetAll<T>(ctrl))
.Concat(controls)
.Where(c => c is T);
}
除了我需要添加 OfType<T>()
外,它工作正常在调用它以访问其属性时。
例如(这个==形式)
this.GetAll<IMyInterface>().OfType<IMyInterface>()
我正在努力将返回类型变成通用返回类型 IEnumerable<T>
, 这样我就不必包含 OfType
这只会返回相同的结果,但会正确转换。
有人有什么建议吗?
(将返回类型更改为 IEnumerable<T>
会导致 Concat
抛出
Instance argument: cannot convert from 'System.Collections.Generic.IEnumerable
<T>
' to 'System.Linq.ParallelQuery<System.Windows.Forms.Control>
'
最佳答案
问题是 Concat
想要一个 IEnumerable<T>
以及 - 不是 IEnumerable<Control>
.这应该可行:
public static IEnumerable<T> GetAll<T>(this Control control) where T : class
{
var controls = control.Controls.Cast<Control>();
return controls.SelectMany(ctrl => GetAll<T>(ctrl))
.Concat(controls.OfType<T>()));
}
关于c# - 通用所有控件方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17454389/