然则,某些场景下,我们须要手写代码转变组件所属的父容器。比方某些组件本来属于父容器A,然则我们想将这些组件调解到父容器B中,此时一个风趣的题目涌现。
以下3个组件本来位于this:
this.Controls.Add(this.operRateUC); this.Controls.Add(this.personProductUg); this.Controls.Add(this.procedingPanel);
想调解这3个组件到adjustPanel组件。以下面的代码所示:
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); } } }
这类批量挪动组件到另一个父组件的体式格局是失利的。
adjustPanel每次新增加了一个组件后,this.Controls的组件就会转变,而且未抛出foreach迭代器被修正的非常。这不晓得是否是微软的一个bug。
在bbs.csdn.net上发帖乞助,复兴,多数以为foreach遍历会报错,然则确实编译器未抛出任何非常。我从新再编译器从新做了一个简朴的测试,效果,发明foreach遍历确实不报错,然则得不到想要的效果。
测试代码以下,测试的预期是将2个Button组件从this中挪动到groupBox1中。然则效果倒是this 中依旧有button1,只要button2被挪动到了groupBox1中。
新鲜点:
foreach迭代器被修正,为何不报错???
为何只要button2挪动到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; }
以上就是.NET框架-详解Winform手艺中组件被容器援用圈套的细致内容,更多请关注ki4网别的相干文章!