无法想到更好的标题,所以抱歉。
我正在尝试转换这个方法,它将检索表单的所有子控件,作为扩展方法并接受接口作为输入。到目前为止我已经达到了
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 == 形式)
this.GetAll<IMyInterface>().OfType<IMyInterface>()
我正在努力将返回类型变成通用返回类型IEnumerable<T>
,这样我就不必包括OfType
它只会返回相同的结果,但转换正确。
有人有什么建议吗?
(将返回类型更改为IEnumerable<T>
导致Concat
扔
实例参数:无法从“System.Collections.Generic.IEnumerable”转换<T>
' 到 '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>()));
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)