设置控制父属性和使用Controls.Add()之间的区别?

时间:2021-03-23 15:52:18

more specifically, are these statements

更具体地说,是这些陈述

ownerControl.GroupBox1.Controls.Remove(childControl);
ownerControl.Controls.Add(childControl);

an equivalent to

相当于

childControl.Parent = ownerControl;

1 个解决方案

#1


Looking in reflector, it looks like Parent just calls Add (when the new parent is non-null). The Controls.Add deals with taking it away from the old parent. So actually, the following are functionally equivalent (when ownerControl is not null):

看看反射器,它看起来像Parent只调用Add(当新的父元素为非null时)。 Controls.Add处理从旧父母那里取走它。实际上,以下是功能相同的(当ownerControl不为null时):

ownerControl.Controls.Add(childControl); // note no Remove etc

and:

childControl.Parent = ownerControl;

Counter-intuitive, but a quick test shows that it works.

反直觉,但快速测试表明它有效。

#1


Looking in reflector, it looks like Parent just calls Add (when the new parent is non-null). The Controls.Add deals with taking it away from the old parent. So actually, the following are functionally equivalent (when ownerControl is not null):

看看反射器,它看起来像Parent只调用Add(当新的父元素为非null时)。 Controls.Add处理从旧父母那里取走它。实际上,以下是功能相同的(当ownerControl不为null时):

ownerControl.Controls.Add(childControl); // note no Remove etc

and:

childControl.Parent = ownerControl;

Counter-intuitive, but a quick test shows that it works.

反直觉,但快速测试表明它有效。