IEnumerable 在循环控件中的工作

working of IEnumerable in for looping controls

任何人都可以帮助我了解这段代码的工作原理。 IEnumarable 如何保存在内存中 var 在这种情况下究竟做了什么?为什么他们在此代码中使用 concat 它到底是什么连接

public IEnumerable<Control> GetAll(Control control,Type type)
{
    var controls = control.Controls.Cast<Control>();
    return controls.SelectMany(ctrl => GetAll(ctrl,type)).Concat(controls) 
                                                         .Where(c => c.GetType() == type);
}

IEnumerable是一个接口。当一个类型实现 IEnumerable 公开一个枚举器时,它可用于通过类型元素进行迭代。

例如一个数组实现了这个接口。因此,您可以使用 foreach 语句遍历它的项目:

foreach(var item in array)
{
    // ...
}

此方法 GetAll return 是一个 Control 对象序列。这可以是 Control 个对象的数组、Control 个对象的列表或实现 IEnumerable<Control> 的每个类型。此方法获取两个对象作为参数,一个是 Control 类型,另一个是 Type 类型。然后在名为 controls 的变量中存储控件中包含的控件集合。有关这方面的更多信息,请查看 here。在此之后,这里:

return controls.SelectMany(ctrl => GetAll(ctrl,type))
               .Concat(controls)
               .Where(c => c.GetType() == type);

你得到的控件中的foreach控件递归包含了同一时间的控件。然后你用 controls 加入两个序列,你 return 它们。

简而言之,如果您向那里传递一个类型为按钮的控件,那么方法 GetAll 将 return 为您提供同一面板中包含的所有按钮的序列。

您可以简单地使用:

 control.Controls.OfType<type>();

如果你想要 controlimmediate 子控件,其类型是 type