在构造函数中或在类的顶部创建一个对象 [英] Create an object in the constructor or at top of the class
问题描述
该声明/实例更好,为什么?
公共类主窗口
{
私人测试_测试;
公共主窗口()
{
_test =新的测试();
}
}
或
公共类主窗口
{
私人测试_test =新的测试();
公共主窗口()
{
}
}
问自己这个问题:当你添加其他构造函数来主窗口
会发生什么?你想,然后要记得提及其他的构造,以确保 _test
是正确初始化?创建UI组件时还是确定为 _test
来,如果使用其他的构造不会被初始化?
个人我会动议故障点多出的构造尽可能的,正如你在选择做我会提出类似的东西要么在加载
事件处理程序,或保持2。
which declaration/instantiation is better and WHY ?
public class MainWindow
{
private Test _test;
public MainWindow()
{
_test = new Test();
}
}
OR
public class MainWindow
{
private Test _test = new Test();
public MainWindow()
{
}
}
Ask yourself this question: what happens when you add other constructors to MainWindow
? Do you want to then have to remember to refer to other constructors to ensure that _test
is correctly initialized? Or is it ok for _test
to not be initialized if another constructor is used?
Personally when creating a UI component i would move as many points of failure out of the constructor as possible, and i would move something like that to either the Loaded
event handler, or keep it as you did in option 2.
这篇关于在构造函数中或在类的顶部创建一个对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!