通用所有控制方法

通用所有控制方法

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

问题描述

想不出更好的标题所以抱歉..

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);
}

除了我需要在调用它以访问其属性时添加 OfType() 之外,它工作正常.

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>()

我正在努力将返回类型变成通用返回类型 IEnumerable,这样我就不必包含 OfType返回相同的结果但正确投射.

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.

大家有什么建议吗?

(将返回类型更改为 IEnumerable 会导致 Concat 抛出

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

实例参数:无法从System.Collections.Generic.IEnumerable"转换为System.Linq.ParallelQuery'

推荐答案

问题是 Concat 也需要 IEnumerable - 而不是 IEnumerable.这应该可以工作:

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>()));
}

这篇关于通用所有控制方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 12:58