这种初始化方法之间的区别是什么?

时间:2021-08-04 19:55:08

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?

preferd是哪个方法?

2 个解决方案

#1


7  

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.

在这种情况下,基类构造函数将在类1中的字段赋值之后调用,但在类2中的赋值之前调用。

#2


2  

The first version allows you to define multiple constructors without having to remember to put the = new SomeType() in each one.

第一个版本允许您定义多个构造函数,而不必记住将= new SomeType()放在每个构造函数中。

#1


7  

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.

在这种情况下,基类构造函数将在类1中的字段赋值之后调用,但在类2中的赋值之前调用。

#2


2  

The first version allows you to define multiple constructors without having to remember to put the = new SomeType() in each one.

第一个版本允许您定义多个构造函数,而不必记住将= new SomeType()放在每个构造函数中。