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
.
第一个版本允许您定义多个构造函数,而不必记住在每个构造函数中放置= new SomeType()
。
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.