To facilitate the development of the content, let me first talk about the construction process of an object.
The construction process for the first instance of a type is generally as follows:
1. Allocates a static member's memory space, at which time the spatial storage data is 0;
2. Executes the initialization statement of the static member;
3. Executes the static constructor of the base class;
4. The static constructor of the execution type;
5. Allocates the memory space of the member, at this time the spatial storage data is 0;
6. The initialization statement of the executing member;
7. Executes the corresponding base class constructor;
8. The constructor for the execution type.
Then for the subsequent creation of the same type, the first 4 steps do not have to be performed, starting with step 5th.
Now, why is it recommended to initialize a member with a member initialization statement? Because member initialization is preceded by a call to a constructor, so early initialization is good for use; second, avoid adding initialization code to the constructor, especially when new members are added, place the initialization in the defined member location, reduce the inconsistency between constructors, and cause some members to be uninitialized. And the member initialization is extracted from the constructor to make the code more concise and clear.
For example:
public class MyList
{
//Init class member here
private ArrayList _List = new ArrayList();
}
Is it possible for all members to initialize this way? In fact, there are three scenarios that do not apply to member initialization in this way.
The first is to assign a member to "0" or "null," which is not a wrong statement, but unnecessary. See the previous object construction process, since members are first allocated memory space and have been initialized with "0" at the same time. Therefore, an explicit assignment increases the instruction operation and affects efficiency.
The second way is to indicate how member initialization is based on different parameters, while the general similar operation is placed in the constructor. If you use a member initialization statement, the member is reinitialized in the constructor, and a transient temporary object is generated.
For example:
public class MyList
{
//Init class member here
private ArrayList _List = new ArrayList();
public MyList()
{}
public MyList( int nSize )
{
_List = new ArrayList( nSize );
}
}