[英]What is the difference between this initialization methods?
What is the difference between this two codes? 这两个代码有什么区别?
class SomeClass
{
SomeType val = new SomeType();
}
and 和
class SomeClass
{
SomeType val;
SomeClass()
{
val = new SomeType();
}
}
Which method is preferd? 选择哪种方法?
There is almost not difference between them. 他们之间几乎没有差别。 The assignment of the field will happen within the constructor in both cases.
在两种情况下,字段的赋值都将在构造函数中发生。 There is a difference in how this happpens in relation to base class constructors though.
但是,与基类构造函数相比,它有多么不同。 Take the following code:
请使用以下代码:
class Base
{
public Base()
{
}
}
class One : Base
{
string test = "text";
}
class Two : Base
{
string test;
public Two()
{
test = "text";
}
}
In this case the base class constructor will be invoked after the field assignment in the class One
, but before the assignment in class Two
. 在这种情况下,基类构造函数将在类
One
的字段赋值之后但在第Two
类中的赋值之前调用。
第一个版本允许您定义多个构造函数,而不必记住在每个构造函数中放置= new SomeType()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.