.net(C#) WinForm development, because it is a visual design, you can directly add a required component to the design interface manually, and .net will automatically initialize this component, including AttributesSettings, etc., are added to InitilizeComponent(), and this component will be added to the corresponding parent component. All of this is done automatically by .net.
However, in some scenarios, we need to write code manually to change the parent container to which the component belongs. For example, some components originally belonged to parent container A, but we want to adjust these components to parent container B. At this time, an interesting problem arises. The following three components were originally located in this:this.Controls.Add(this.operRateUC); this.Controls.Add(this.personProductUg); this.Controls.Add(this.procedingPanel);
adjustPanel component. As shown in the following code:
private void moveToAdjustPanel() { //AdjustablePanel是一个Control类 AdjustablePanel adjustPanel = new AdjustablePanel(); foreach (Control ultraControl in this.Controls) { if (ultraControl.GetType() == typeof(UltraGrid) || ultraControl.GetType() == typeof(UltraChart) || ultraControl.GetType() == typeof(Panel)) { adjustPanel.Controls.Add(ultraControl); } } }
Every time adjustPanel adds a new component, the component of this.Controls will change,
and no exception that the foreach iterator is modified will be thrown. I don’t know if this is a Microsoft bug.
The foreach iterator is modified, why does it not report an error? ? ?
Why is only button2 moved to groupBox1? ? ?
public Form1() { InitializeComponent(); moveButtonsToGroupBox(); //controlNames的结果为{groupBox1,button1} var controlNames = showAllChildControls(this); //controlNamesInGroup的结果为{button2} var controlNamesInGroup = showAllChildControls(this.groupBox1); } /// <summary> /// 移动位于Form上的按钮到GroupBox中 /// </summary> private void moveButtonsToGroupBox() { foreach(Control c in this.Controls) { if (c.GetType() == typeof(Button)) this.groupBox1.Controls.Add(c); } } /// <summary> /// 展示c控件的所有子组件的Name /// </summary> /// <param name="c"></param> /// <returns></returns> private List<string> showAllChildControls(Control c) { if (c == null) return null; List<string> controlNames = new List<string>(); foreach(Control chl in c.Controls) { controlNames.Add(chl.Name); } return controlNames; }
The above is the detailed content of .NET Framework - Detailed explanation of the trap of components being referenced by containers in Winform technology. For more information, please follow other related articles on the PHP Chinese website!