我有以下函数来获取类型的所有子控件。
private IEnumerable<Control> GetControlsOfType(Control control, Type type)
{
var controls = control.Controls.Cast<Control>();
return controls.SelectMany(ctrl => GetControlsOfType(ctrl, type))
.Concat(controls)
.Where(c => c.GetType() == type);
}
我正在尝试使用泛型类型参数对其进行转换。
private IEnumerable<T> GetControlsOfType<T>(Control control) where T: Control
{
var controls = control.Controls.Cast<Control>();
return controls.SelectMany(ctrl => GetControlsOfType<T>(ctrl))
.Concat(controls)
.Where(c => c.GetType() == T);
}
代码在.Concat
上有错误.
Error 6 'System.Collections.Generic.IEnumerable
<T
>' does not contain a definition for 'Concat' and the best extension method overload 'System.Linq.Queryable.Concat<TSource
>(System.Linq.IQueryable<TSource
>, System.Collections.Generic.IEnumerable<TSource
>)' has some invalid arguments
如何解决这个问题?
最佳答案
尝试添加 .OfType<Control>()
在 GetControlsOfType<T>(ctrl)
之后而不是你的 Where
所以你的代码是这样的:
return controls.SelectMany(ctrl => GetControlsOfType<T>(ctrl).OfType<Control>())
.Concat(controls)
.OfType<T>();
关于c# - 获取控件类型为 T 的子控件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13567875/