C # constructor and destructor usage

Source: Internet
Author: User
Tags types of functions

Constructor and destructor are two seemingly simple types of functions in a class, but some unexpected running errors will always occur during actual use. This document introduces the principles of constructor and destructor systematically.
And the use of C #, as well as a number of precautions during use.

C # Constructor
Constructor is a special member function. , It is mainly used to allocate storage space for objects. , Initialize data members .

(1) The name of the constructor must be the same as that of the class. ; (2) No return type for the constructor , It can contain parameters , You can also leave the parameter unspecified. ; (3) The main function of the constructor is to complete class initialization. ; (4) When creating a new class Object (using the new keyword), the system automatically calls back to the class constructor to initialize the new object. ;

the C # class has two constructor types: instance constructor and static constructor
instance constructor: initializes instance variables in the class, it is called only when the user uses the New Keyword to allocate memory for the object and serves as a class of reference type, the instantiated objects must be allocated to the
managed
heap. The instance constructor is divided into default constructor and non-default constructor. Note that once the class has its own constructor, the default constructor will be invalid no matter whether there are parameters or no parameters,
A constructor is not called if you only name a class without instantiating it. static constructor: (1) initialize static and read-only fields;
(2) Add a static keyword, but do not add access modifiers because static constructors are private.
(3) the static constructor of the class can be executed at most once in the Program Field of the given application, only the instance of the created class or any static member of the referenced class is triggered. parameters cannot be included.
(4) static constructors cannot be inherited and cannot be called directly.
(5) if the class contains the main method used to start execution, the static constructor of this class will be executed before the main method is called. ren What are the static fields with the Initial Value Setting items? When you execute the static constructor of this class, you must first execute the initial values in the text order.
(6) if a static constructor is not compiled, and the class contains a static field with an initial value, the compiler automatically generates the default static constructor; A class can have both the instance constructor and static constructor. This is the only situation where methods with the same name can coexist with the same parameter list.

Since: http://tb.blog.csdn.net/TrackBack.aspx? Postid = 1622612

I. constructor and destructor principles

As a more advanced language than C, C # provides a better mechanism to enhance program security. C # the compiler has strict
The type security check function can almost find out all the Syntax problems in the program, which indeed helps programmers a lot. However, if the program passes the compilation check, it does not indicate that the error does not exist.
"Syntax error" is only 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 variable failures.
The initialization and cleanup tasks are easily forgotten because they are correctly initialized or cleared. Microsoft fully considered this problem when designing the C # language using the object-oriented concept and solved it well:
The initialization work is put in the constructor, And the cleanup 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 don't have to worry about forgetting objects.
.

II. Application of constructor in C #

The name of the constructor must be recognized by the compiler.
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 similar to that of the return value type void.
Different 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.

The following lists several types of constructors.

1) default constructor

Class Testclass
{
Public Testclass (): Base (){}
}

As described above, it is provided by the system (CLR.

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 ;
}

PublicPoint (DoubleX,DoubleY)
{
This. X=X;
This. Y=Y;
}
...
}

Class Test
{
Static   Void Main ()
{
Point =   New Point ();
Point B =   New Point ( 3 , 4 ); // Object initialization using Constructors
...
}
}

Declares a class point, which provides two constructors. They are overloaded. A point constructor without parameters and a point constructor with two double parameters
Number. If the constructor is not provided in the class, the CLR automatically provides a default constructor. However, once the class provides custom constructors, such as point () and point
(Double X, Double Y), the default constructor will not be 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 (...);
}
...
}

Declared a class of employee with a static constructor. Note that the static constructor can only

Static data members cannot be initialized. 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 create a private constructor: Private testclass (){...}, However, private 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 creating an object of A derived class, the system will call the constructor of the base class and the constructor of the derived class. The execution sequence of the constructor of the base class is: first execute the constructor of the base class, 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 A
{ 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 (); // Execute the constructor A () of the base class A, and then execute the constructor B () of the derived class ()
B B2 =   New B ( 1 ); // Execute the constructor A () of the base class A, and then execute the constructor B (INT) of the derived class)
B B3 =   New B ( 0 , 1 ); // Execute the constructor A (INT) of the base class A, and then execute

Constructor B (INT, INT)
Here, the execution sequence of the constructor must be clearly analyzed. In addition, if the base class A does not provide the non-argument constructor public a () {x = 0 ;}, in the initialization table of all constructors in the derived class, the constructors A (I) of the base class A must be pointed out as follows:

Class A
{ 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. Application of destructor and garbage collector in C #

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, the prefix '~ 'To show the difference.

Although C # (more specifically, CLR) provides a new memory management mechanism-the Automatic Memory Management Mechanism
Management), resources can be released through the "Garbage Collector"
Generally, no user intervention is required. However, in some special cases, destructor are required, such as the release of unmanaged resources in C.

Resources are automatically released through the "Garbage Collector", but there are still some points to note:

1. the reference of the value type and reference type does not need any "Garbage Collector" to release the memory, because when they are out of scope, the occupied memory will be automatically released, because they are all stored in stacks;

2. only the object instances referenced by reference types are stored in heap. Because heap is a free storage space, therefore, it does not have a life period like the "stack" (after the "stack" element pops up, it indicates that the life period ends and the memory is released). Note that, the "Garbage Collector" only applies to this area;

However, in some cases, you must writeCode. It is usually to use destructor to release unmanaged resources and release the Code Compiled by the user.
The segment can be placed in the destructor. Note that if an unmanaged resource is not used in a class, do not define the Destructor because the object executes the destructor.
Before releasing managed resources, you must 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 two actions. The following code shows how the Destructor is used.
Of:

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 understand the CLR memory management mechanism and better manage system resources.

Note:CLR
The CLR (Common Language Runtime Library) is also a runtime environment like the Java Virtual Machine. It manages resources (memory allocation and garbage collection) and ensures necessary separation between applications and underlying operating systems.
To improve the reliability of the platform and the stability level required by transaction-oriented e-commerce applications, CLR is also responsible for other tasks, such as monitoring program running. According to. net,
Programs running under CLR monitoring belong to "managed" code, but applications or components running under Clr and directly on bare metal belong to "unmanaged"
(Unmanaged) code.
CLR will monitor various common programming errors. These errors have been the main source of software faults for many years, including access to array elements out of bounds and access to unallocated memory space, memory overflow caused by a large data volume.


Self: http://www.yesky.com/351/1755351_2.shtml

Related Article

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.