1. Create the instance value directly while declaring the variable in a class. Includes static and instance variables
Example: Object m_o = new Object ();
It is not recommended to do this when: the first type of value.
int i=new int ();//Generates boxing
The second kind. Two constructors. You may have questions about this situation, aren't you suggesting that you initialize it? Why this is not recommended here.
The reason: when you create a new MyClass object, specifically specifying the size of the collection, you create a list of two arrays. One of them quickly became a garbage object.
public class MyClass { private ArrayList _coll = new ArrayList (); MyClass () {}//constructor and is 2 MyClass (int size) {_coll = new ArrayList (size);}}
2. Use static constructors to initialize static members. (found no, this is contrary to the above-mentioned reason the author says: Because of the exception, static constructors often replace the static preset method )
A singleton design pattern is implemented using this method.
3. Write a good constructor. Examples are as follows
public class myclass{ private ArrayList _coll; private string _name; Public MyClass (): This (0, "") {} public MyClass (int. initialcount): This (Initiacount, "") {} public MyClass (int i Nitialcount, string name) { _coll = (initialcount > 0)? new ArrayList (initialcount): New ArrayList ();
_name = name; } }
4. The order in which a type first constructs an instance: 1, static variable storage location 0. 2, static variable preset method execution (that is, the initialization of the syntax). 3, the static constructor of the base class executes. 4, static constructor execution. 5, instance variable storage location 0. 6, the instance variable preset method executes. 7. The appropriate base class instance constructor executes. 8, the instance constructor executes. Subsequent instances of the same type start with the 5th step because the class's preset method executes only once.
effectivec#12,13,14--member Initialization