Principles and Application of constructor and destructor in C #

Source: Internet
Author: User
Abstract   To: Constructor and destructor are two seemingly simple functions in a class. But there will always be some unexpected running errors in the actual application process. This article will be a more systematic introduction The principles of constructor and destructor C # And several things that need to be paid attention to during use.

Keywords:Constructor; destructor; garbage collector; unmanaged resources; managed resources

I. constructor and destructor principles

As RatioCMore advanced languages,C #Provides a better mechanism to enhanceProgramSecurity.C #The compiler has a strict type security check function, which can almost find all the Syntax problems in the program, which indeed helps programmers. However, after the program passes the compilation check, it does not mean that the error does not exist. In the "error" family, the "syntax error" status can only be regarded as the tip of the iceberg. High-level errors are often hidden in depth and cannot be easily discovered.

Based on experience, many program errors that are hard to detect are caused by the variable being correctly initialized or cleared, and initialization and cleanup are easily forgotten. Microsoft uses the object-oriented concept to designC #This problem is fully taken into account in the language and well solved: the initialization work of the object is put in the constructor, And the cleaning work is put in the destructor. When an object is created, the constructor is automatically executed. When an object dies, the Destructor is automatically executed. In this way, you do not have to worry about the initialization and clearing of objects.

2. constructor inC #Application in

The name of the constructor cannot start at will. It must be recognized by the compiler before it can be automatically executed. Its naming method is simple and reasonable: Let the constructor and class have the same name. Except for the name, the constructor has no return value type, which is different from the return value type.VoidDifferent functions. If it has a return value type, the compiler will be overwhelmed. Before you can access a class's methods, attributes, or anything else, The first statement to be executed contains the constructor of the corresponding class. Even if you do not write a constructor, a default constructor is provided to you.

Class testclass

{

Public testclass (): Base (){}//ByCLRProvide

}

The following lists several types of constructors.

1)Default constructor

 Class testclass

{

Public testclass (): Base (){}

}

As described above, it is composed.

 

2) Instance Constructor

An instance constructor is a method member that initializes an instance in a class. For example:

Using system;

Class Point
{
Public Double X, Y;

Public point ()

{
This. x = 0;
This. Y = 0;
}

Public point (Double X, Double Y)

{
This. x = X;
This. Y = y;
}

 ...

}

Class Test
{
Static voidMain()

{
Point A = new point ();
Point B = new point (3, 4 );//Object initialization using Constructors
...

}
}

Declared a classPointIt provides two constructors. They are overloaded. One has no parameters.PointThere are two constructor and one isDoubleParameterPointConstructor. If the constructor is not provided in the classCLRA default constructor is automatically provided. However, once the class provides a custom constructor, suchPoint ()AndPoint (Double X, Double Y)The default constructor is not provided.

 

3)Static Constructor

A static constructor is a method member that initializes a class. It is generally used to initialize static data. Static constructor cannot have parameters, modifiers, and call. When a class is loaded, the static constructor of the class is automatically called. For example:

Using system. Data;

Class employee
{
Private Static dataset Ds;

Static employee ()

{
DS = new dataset (...);
}

...
}

Declares a class with a static constructor.Employee. Note: static constructors can only initialize static data members, but not non-static data members. However, non-static constructors can assign values to static data members or initialize non-static data members.

If the class only contains static members, you can createPrivateConstructor:Private testclass (){...},PrivateIt means that it is impossible to access the constructor from outside the class. Therefore, it cannot be called and no object can be instantiated by the class definition.

The above is a simple application of several types of constructor. The following describes how to use the base class and the constructor of the derived class in the class hierarchy (that is, the inheritance structure. The initialization of a derived class object is completed by the base class and the derived class. The base class members are initialized by the base class constructor, and the members of the derived class are initialized by the constructor of the derived class.

When you create an object of A derived class, the system calls the constructor of the base class and the constructor of the derived class.The execution order of the function creation is: first execute the constructor of the base class, and then execute the constructor of the derived class. If the derived class has another object Member, first execute the constructor of the base class, then execute the constructor of the member object class, and finally execute the constructor of the derived class.

As for the constructors that execute the base class, the base class constructor is executed by default. If you want to execute the base class constructor with parameters, it must be specified in the member initialization table of the derived class constructor. For example:

Class

{Private int X;

Public A () {x = 0 ;}

Public A (int I) {x = I ;}

};

 

Class B:

{Private int y;

Public B () {Y = 0 ;}

Public B (int I) {Y = I ;}

Public B (int I, Int J): A (I) {Y = J ;}

};

 

B b1 = new B ();//Execution base classAOfConstructorA (), And then executeConstructor of a derived classB ()

B b2 = new B (1 );//Execution base classAOfConstructorA (), And then executeConstructor of a derived classB (INT)

B B3 = new B (0, 1 );//Execution base classAOfConstructorA (INT), And then executeDerived class

ConstructorB (INT, INT)

Here, the execution sequence of the constructor must be clearly analyzed. In addition, ifBase ClassANot providedNo-argument ConstructorPublic A () {x = 0 ;}InThe initialization table of all constructors in the derived class must specify the Base Class.Parameter constructorA (I), As shown below:

Class

{Private int X;

Public A (int I) {x = I ;}

};

Class B:

{Private int y;

Public B (): A (I) {Y = 0 ;}

Public B (int I): A (I) {Y = I ;}

Public B (int I, Int J): A (I) {Y = J ;}

};

Iii. destructor and Garbage CollectorC #Application in

A destructor is a method member that destroys an instance of a class. The Destructor cannot have parameters, any modifiers, and cannot be called. Because the purpose of the Destructor is opposite to that of the constructor, prefix'~'To show the difference.

AlthoughC #(More specificallyCLR) Provides a new memory management mechanism.---Automatic Memory Management (Automatic Memory Management), The resource can be released through the "Garbage Collector" Generally, no user intervention is required. However, in some special cases, you still need to use the destructor, as shown inC #Release of unmanaged resources.

Resources are usually released through"Garbage Collector"Automatically completed,But specifically,Note the following:

1.The reference of the value type and reference type does not actually need any"Garbage Collector"To release the memory,Because when they are out of scope, the occupied memory is automatically released because they are all stored on the stack.(Stack)Medium;

2.Heap exists only when the reference type refers to the object instance.(HEAP)Medium,Heap is a free storage space.,So it does not look like"Stack"That has a life period.("Stack"After the element pops up, the lifetime ends.,This means that the memory is released.),Note that,"Garbage Collector"It only works for this region;

However,In some cases, when an unmanaged resource needs to be released,You must writeCode. Usually, you can use the destructor to release the unmanaged resources and place the code snippet that you write to release the unmanaged Resources in the destructor. Note that,If an unmanaged resource is not used in a class,Do not define destructor,This is because the object executes the destructor.,So"Garbage Collector"Before releasing managed resources, you need to call the Destructor and then release the managed resources for the second time. In this way, the cost of the two Delete actions is much higher than that of the other actions. The following code shows how the Destructor is used:

Public class resourceholder

{

...

~ Resourceholder ()

{

//Here is the user code segment for clearing unmanaged Resources

}

}

Iv. Summary

Although constructor and destructor are relatively simple functions in the form of a class, their use is never as simple as it looks, therefore, flexible and correct use of constructors and destructor can help you better understandCLRMemory Management Mechanism and better management of system resources.

 

References:

[1]Microsoft,China East. C #Language Reference Manual[M].Beijing: Tsinghua University Press,2001

[2] Simon Robinson, Ollie Cornes. C #Advanced Programming[M].Kang Bo.Beijing: Tsinghua University Press,2002

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.