Winforms 表单构造函数与加载事件
当表单加载时,代码需要执行诸如设置数据网格、组合框、设置标题等操作。我倾向于始终使用 load 事件而不是 new (构造函数)。 是否有关于哪种活动最适合哪种活动的指南?
When a form loads, the code needs to do things like setup datagrids, comboboxes, set the title, etc. I've tended to always use the load event rather than the new (constructor). Are there any guidelines for which one is best for which activities?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
对 InitializeComponent 的调用会自动插入到表单/页面的构造函数中。 InitializeComponent 是自动生成的方法,它
,因此与 UI 安排/修改相关的任何内容都应该在此调用之后进行。 。 当您在 Form.OnLoad 的重写中执行此操作时,您可以放心 UI 已准备就绪(已调用 InitializeComponent)...因此我投票支持坚持 UI 的 OnLoad。
创建非 UI 成员时,构造函数将是我首先查看的地方。
A call to InitializeComponent is automatically inserted in the constructor of your form/page. InitializeComponent is the auto-generated method that
So anything related to UI arrangement/modifications should go after this call. When you do this in an override of Form.OnLoad , you're assured that the UI is ready to go (InitializeComponent has been called)... so I'd vote for sticking to OnLoad for UI.
Creating non-UI members, constructor would be the place I'd first look at.
请记住,表单构造函数中的任何内容都将在该表单创建时创建/执行。 即:
Form frm = new Form();
而只有当表单显示时,加载事件中的任何事情才会发生,即
frm.Show();
Bear in mind that anything in the constructor of a form will be created/executed at that forms creation. i.e. at:
Form frm = new Form();
Whereas anything in the Load event will occur only when the form is shown i.e.
frm.Show();
基本上你希望你的构造函数尽可能轻量。 我尝试将大部分内容放入 Load 事件处理程序中,因为 UI 元素已创建并且此时可用。 但是,我通常在构造函数中实例化类对象等,因为它实际上是构造对象的一部分。 有时你不能把东西放在一个地方或另一个地方,但在可以的时候,你应该把它们放在看起来最合适的地方。
Basically you want your constructor to be as light-weight as possible. I try to put most things in the Load event handler as the UI elements have been created and are usable at this time. However, I usually instantiate class objects etc. in the constructor as it is actually part of constructing the object. Sometimes you can't put things in one place or the other but for the times when you can, you should just put them where it seems most appropriate.