Form_Load() '事件' 或覆盖 OnLoad() [英] Form_Load() 'event' or Override OnLoad()

查看:28
本文介绍了Form_Load() '事件' 或覆盖 OnLoad()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望有人尝试解释这些之间的区别.更具体地说,示例使用场景.

I would like someone to try and explain the difference between these. More specifically, example usage scenario's.

我正在重构一些 Windows Form 代码,并且一个 FormForm_Load() 事件和 中都有一些代码protected override void OnLoad() 事件调用 base.OnLoad(e); 现在我跟踪了它,Override 首先触发,然后立即触发事件版本.

I am refactoring some Windows Form code and a Form has some code in the Form_Load() event and also in a protected override void OnLoad() event that calls base.OnLoad(e); Now I traced it and the Override fires first and then immediately fires off the event version.

那么,通常使用哪一种,为什么?

So, which one is typically used and why?

推荐答案

你应该总是重写 OnLoad().仅当另一个 类对该事件感兴趣时才适合使用该事件.这是什么事件.另一个对 Load 事件感兴趣的类非常少见,只对做窗口排列的东西很有用.

You should always override OnLoad(). Using the event is only appropriate when another class would be interested in the event. Which is what events are for. Another class being interested in the Load event is very rare, only really useful to do window arrangement stuff.

尽管如此,Load 事件对设计者来说效果很好,而且 VB6 程序员对它非常满意.这并没有大错,只有当您开始继承表单并且代码没有按正确顺序运行时,您才会遇到麻烦.

Still, the Load event works well with the designer and VB6 programmers are very comfortable with it. It isn't horribly wrong, you'd only get in trouble when you start inheriting the form and code doesn't run in the right order.

现在放入 Load 事件中的大多数代码实际上都属于构造函数.仅在以下情况下才需要 OnLoad:

Most code that now gets put in the Load event really belongs in the constructor. You only need OnLoad if:

  • 您需要知道窗口的确切大小和位置.OnLoad 最好,创建窗口句柄并应用用户首选项(标题和边框大小),并按照 Form.AutoScaleMode 属性的指示重新缩放表单.该窗口尚不可见,这是将窗口移至其他位置或安排子控件的好时机.
  • 您有需要 Handle 属性的代码.这是微妙的,你不能总是说出来.在构造函数中拥有这样的代码是不健康的,窗口在构造函数完成之前被创建.它通常会有一个好的结局,但它会使创建表单非常缓慢.易于从调用堆栈"窗口进行诊断.
  • 为了避免 MDI 实现中的错误.如果您在父构造函数中创建 MDI 子项,那么您将获得重复的字形,当您最大化子项时可见.而是在 OnLoad 中创建子项.

这篇关于Form_Load() '事件' 或覆盖 OnLoad()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆