你可以这样做:
public static void ForAllChildren(Action<Control> action,
params Control[] parents)
{
foreach(var p in parents)
foreach(Control c in p.Controls)
action(c);
}
像这样调用:
ForAllChildren(x => Foo(x), tb_Invoices, tb_Statements);
尽管在这种情况下您可以只使用嵌套的,但您可能会在操作调用的性能上受到一点影响foreach
:
foreach (var p in new Control[] { tb_Invoices, tb_Statements })
foreach (Control c in p.Controls)
Foo(c);
同样,遍历任何非泛型中所有项目的通用解决方案IEnumerable
可能是(尽管有点像使用大锤敲钉子):
public static void ForEachAll<T>(Action<T> action,
params System.Collections.IEnumerable[] collections)
{
foreach(var collection in collections)
foreach(var item in collection.Cast<T>())
action(item);
}
像这样调用:
ForEachAll<Control>(x => Foo(x), tb_Invoices.Controls, tb_Statements.Controls);