通用所有的方法控制 [英] Generic All Controls Method

查看:119
本文介绍了通用所有的方法控制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也想不出更好的标题,所以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 a OfType which will just return the same result but cast correctly.

Anyone have any suggestions?

(Changing return type to IEnumerable<T> causes the Concat to throw

Instance argument: cannot convert from 'System.Collections.Generic.IEnumerable<T>' to 'System.Linq.ParallelQuery<System.Windows.Forms.Control>'

解决方案

The problem is that Concat would want an IEnumerable<T> as well - not an IEnumerable<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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆