The role of BeginInit() and EndInit() methods in Designer

社会主义新天地 提交于 2021-02-04 22:11:49

问题


I've red that those methods of ISupportInitialize interface are used by Designer to support optimization, to ensure atomicity of initialization of controls, and to prevent any action on controls during initialization. My questions are:

  1. In what way they help Designer to optimize initialization of controls?
  2. Why to ensure atomicity of initialization?
  3. Is there any reasonable example when to use them in code not generated by Designer?

回答1:


It does not have anything to do with optimization. ISupportInitialize is an interface that you need when your control is sensitive to the order in which properties are assigned. There isn't any way to affect the order in which the designer assigns them, it does it alphabetically.

You typically set a bool variable to true in your BeginInit() method, you test this in the property setters and don't do anything when it is set. Your EndInit() method then makes the property values effective.

You can see a good example of this in the ErrorProvider component. Note how it uses the methods to defer data binding. The PictureBox control is another good example, it uses it to defer image downloading. TrackBar is yet another example, it uses it to ensure that the Value property is between Minimum and Maximum. Etcetera, the .NET Framework source is often a very good place to see how .NET types are used in practice.




回答2:


By definition the Designer permits to create controls in a visual mode, the appropriate code to initialize the controls is then generated by Visual Studio.

The initialization is done in one place to avoid any null reference issue later in your code. You expect indeed every controls already created when you use their reference.

You perfectly can create your controls initialization if for example you want to dynamically create your interface based on a specific constructor.



来源:https://stackoverflow.com/questions/30462788/the-role-of-begininit-and-endinit-methods-in-designer

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!