General understanding of C #(23. constructor and destructor)

Source: Internet
Author: User

23. constructor and destructor

You can specify the optional constructor parameters:

Class Test

{

Public Test (): this (0, null ){}

Public Test (int x, object o ){}

}

You can also specify the static constructor:

Class Test

{

Static int [] ascendingArray = new int [100];

Static Test ()

{

For (int I = 0; I <ascendingArray. Length; I ++)

AscendingArray [I] = I;

}

}

The name of the Destructor adopts the naming convention C ++ ~ Symbol. The Destructor can only be applied to reference types, value types are not allowed, and cannot be overloaded. The Destructor cannot be explicitly called because the object's life cycle is controlled by the garbage collector. Before the memory occupied by an object is recycled, each destructor in the Object Inheritance layer will be called.

Although similar to C ++, The destructor in C # is more like the finalize method in Java. This is because they are all called by the garbage collector rather than explicitly called by the programmer. Moreover, like Java's finalize, they cannot be guaranteed to be called in various circumstances (this is often the first time everyone who discovers this is shocked ). If you are used to the deterministic destructor programming mode (You know when the object's destructor is called), when you move to Java or C, you must adapt to this different programming model. What Microsoft recommends and implements throughout the. NET Framework is the dipose model. You need to define a dispose () method for the classes of external resources (shape handles or database connections) that need to be managed. For distributed programming, the. NET Framework provides an agreed basic model to improve the reference counting problem of DCOM.

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.