控件
将以下类添加到您的项目中:
public static class ControlExtensionMethods
{
public static IEnumerable<Control> GetOffsprings(this Control @this)
{
foreach (Control child in @this.Controls)
{
yield return child;
foreach (var offspring in GetOffsprings(child))
yield return offspring;
}
}
}
它将返回调用者的所有子控件:
var offsprings = this.GetOffsprings();
您可以在循环中使用它:
foreach (Control c in this.GetOffsprings())
{
// Do action
}
菜单项
将以下类添加到您的项目中:
public static class MenuStripExtensionMethods
{
public static IEnumerable<ToolStripItem> GetSubItems(this ToolStrip @this)
{
foreach (ToolStripItem child in @this.Items)
{
yield return child;
foreach (var offspring in child.GetSubItems())
yield return offspring;
}
}
public static IEnumerable<ToolStripItem> GetSubItems(this ToolStripItem @this)
{
if (!(@this is ToolStripDropDownItem))
yield break;
foreach (ToolStripItem child in ((ToolStripDropDownItem) @this).DropDownItems)
{
yield return child;
foreach (var offspring in child.GetSubItems())
yield return offspring;
}
}
}
它将返回调用者的所有子菜单项:
var allMenuItems = this.menuStrip1.GetSubItems()