You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现返回控件所有指定类型父控件的IEnumerable<T>扩展方法?

实现返回所有匹配父控件的C#扩展方法FindControlParents

你现有的FindControlParent<T>方法仅能返回第一个匹配的父控件,要实现返回所有符合类型的父控件,我们可以利用yield return遍历整个控件层级,收集所有匹配结果:

原方法代码

public static T FindControlParent<T>(this Control control) where T : Control
{
    T parent = default;
    if (control.Parent != null)
    {
        if (control.Parent.GetType() == typeof(T))
        {
            return (T)control.Parent;
        }
        return FindControlParent<T>(control.Parent);
    }
    return parent;
}

新的FindControlParents实现

public static IEnumerable<T> FindControlParents<T>(this Control control) where T : Control
{
    var currentParent = control.Parent;
    while (currentParent != null)
    {
        if (currentParent is T matchedControl)
        {
            yield return matchedControl;
        }
        currentParent = currentParent.Parent;
    }
}

代码说明

  • 用while循环遍历控件的父层级,直到没有父控件为止
  • 使用is运算符做类型检查并直接转换,相比GetType() == typeof(T)更灵活,支持派生类型匹配
  • 通过yield return逐个返回匹配的父控件,最终返回IEnumerable<T>类型结果

使用示例

针对你的控件层级Form>panel1>panel2>GroupBox>button,调用方式如下:

var panelsFound = button1.FindControlParents<Panel>();

执行后panelsFound会包含panel2和panel1(遍历顺序从直接父控件往上,先返回panel2,再返回panel1)

内容的提问来源于stack exchange,提问作者Caio Souza

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 04:55:25