通用所有的方法控制 [英] Generic All Controls Method
问题描述
也想不出更好的标题,所以appologies ..
我想转换这种方法,这将检索一个表单的所有子控件,是一个延伸方法以及接受接口为输入。到目前为止,我最多
公开的IEnumerable<控制> GETALL< T>(这种控制的控制),其中T:类
{
无功控制= control.Controls.Cast<控制>(); 返回controls.SelectMany(CTRL =>&GETALL LT; T>(CTRL))
.Concat(对照)
。凡(C => c为T);
}
这工作正常但我需要添加 OfType< T>()
调用它的时候去其属性访问
例如(此==表格)
this.GetAll< IMyInterface的>()OfType< IMyInterface的>()
我努力使返回类型为一个通用的返回类型的IEnumerable< T>
,这样我就不必包含 OfType
这将只返回相同的结果,但正确地投。
任何人有什么建议吗?
(改变返回类型为的IEnumerable< T>
引起的毗连
扔
实例参数:无法从转换'System.Collections.Generic.IEnumerable
< T>
'到'System.Linq.ParallelQuery< System.Windows.Forms.Control的>
块引用>解决方案的问题是,
的毗连
想一个的IEnumerable< T>
,以及 - 不是的IEnumerable<控制>
。这应该工作,虽然:公共静态的IEnumerable< T> GETALL< T>(这种控制的控制),其中T:类
{
无功控制= control.Controls.Cast<控制>(); 返回controls.SelectMany(CTRL =>&GETALL LT; T>(CTRL))
.Concat(controls.OfType< T>()));
}Couldn't think of a better title so appologies..
I'm trying to convert this method, which will retrieve all child controls of a form, to be an extension method as well as accept interfaces as inputs. So far I am up to
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); }
which works fine except I need to add
OfType<T>()
when calling it to get access to its properties.e.g (this == form)
this.GetAll<IMyInterface>().OfType<IMyInterface>()
I'm struggling to make the return type into a generic return type
IEnumerable<T>
, so that I don't have to include aOfType
which will just return the same result but cast correctly.Anyone have any suggestions?
(Changing return type to
IEnumerable<T>
causes theConcat
to throwInstance argument: cannot convert from 'System.Collections.Generic.IEnumerable
<T>
' to 'System.Linq.ParallelQuery<System.Windows.Forms.Control>
'
解决方案The problem is that
Concat
would want anIEnumerable<T>
as well - not anIEnumerable<Control>
. This should work though: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>())); }
这篇关于通用所有的方法控制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!