应该在哪里的InitializeComponent()出现在代码顺序? [英] Where should InitializeComponent() appear in code order?

查看:171
本文介绍了应该在哪里的InitializeComponent()出现在代码顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我创建一个WinFormsmyForm会则生成以下锅炉板代码:

If I create a winForms "myForm" then the following boiler plate code is generated:

public partial class myForm: Form
{
    public myForm() 
    {

       //<<position 1

       InitializeComponent();

       //<<position 2

    } 
}

如果我增加额外的代码,构造函数方法并使其向,如果我把我的代码在位置1或2的应用程序的运行有什么区别?

If I add extra code to the constructor method does it make any difference to the running of the app if I place my code in position 1 or 2 ?

推荐答案

是的,是的。

的InitializeComponent 是VS生成负责创建和定位一个窗体上的控件的方法。

InitializeComponent is the method that VS generates that is responsible for creating and positioning the controls on a form.

守则位置1将执行存在控件之前。如果试图在这个位置访问控制,你会得到一个的NullReferenceException (比方说,如果你尝试设置文本框的内容)。 。如预期中的位置2类似的代码将工作

Code in "position 1" will execute before the controls exist. If you try to access a control in this position, you'll get a NullReferenceException (say, if you try to set the content of a TextBox). Similar code in "position 2" will work as expected.

有是使用中位置1是:如果你有依赖的性质自定义控件或行为的的形式,在位置1设置这些属性可能会阻止该代码不必刷新,如果你允许设置这些值之前创建的控件。

There is use to "position 1" though: if you have custom controls or behaviour that rely on properties of your form, setting those properties in "position 1" might prevent that code from having to refresh if you allow controls to be created before those values are set.

这篇关于应该在哪里的InitializeComponent()出现在代码顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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