C # Basic Knowledge series 5 (constructor)

Source: Internet
Author: User

This section describes the instance constructor, private constructor, and static constructor. The role of constructor: 1. When a class is new to instantiate an object, you can call constructor to initialize the object. 2. A constructor without parameters is called a "default constructor ". Whenever you use the new operator to instantiate an object without providing any new parameters, the default constructor is called. Unless the class is static, the C # compiler provides a common default constructor for classes without constructor so that the class can be instantiated. 3. You can set the constructor as a private constructor to prevent classes from being instantiated. 4. the constructor of the structure type is similar to the constructor of the class, but structs cannot contain the explicit default constructor, because the compiler will automatically provide a constructor. This constructor initializes each field in struct to the default value. This default constructor is called only when struct is instantiated with new. When an instance constructor uses the new expression to create an object of a class, it uses the instance constructor to create and initialize all instance member variables. To initialize static variables in a static or non-static class, you must define a static constructor. Copy the code class CoOrds {public int x, y; // constructor public CoOrds () {x = 0; y = 0 ;}} copy the code as long as you create an object based on the CoOrds class, the constructor of this instance is called. Such constructors without parameters are called "default constructor ". However, it is usually useful to provide other constructors. For example, you can add constructors to the CoOrds class so that you can specify the initial value for data members: public CoOrds (int x, int y) {this. x = x; this. y = y ;}then you can use the default or specific initial values to create a CoOrd object, as shown below: CoOrds p1 = new CoOrds (); CoOrds p2 = new CoOrds (5, 3 ); if a class has no constructor, a default constructor is automatically generated and the default value is used to initialize the object field. You can also use the instance constructor to call the base class instance constructor. The class constructor can call the base class constructor through the initial value setting item, as shown below: copy the code abstract class Shape {public const double pi = Math. PI; protected double x, y; public Shape (double x, double y) {this. x = x; this. y = y;} public abstract double Area ();} class Circle: Shape {public Circle (double radius): base (radius, 0) {} public override double Area () {return pi * x;}. In this example, the Circle class passes the radius and height value to the constructor provided by Shape (derived from Circle. Private constructor is a special instance constructor. It is usually used in a class that only contains static members. If a class has one or more private constructors without a public constructor, other classes (except Nested classes) cannot create instances of the class. For example, copy the code class NLog {// Private Constructor: private NLog () {} public static double e = Math. e; // 2. 71828 ...} copy the code declaration empty constructor to Prevent Automatic Generation of default constructor. Note: if you do not use an access modifier for the constructor, it is still a private constructor by default. However, the private modifier is explicitly used to explicitly indicate that the class cannot be instantiated. When there are no instance fields or instance methods (such as the Math class) or when a method is called to obtain an instance of the class, the private constructor can be used to block the creation of the instance of the class. If all the methods in the class are static, consider making the entire class static. The following is an example of a class using a private constructor: copy the code public class Counter {private Counter () {} public static int currentCount; public static int IncrementCount () {return ++ currentCount ;}} class TestCounter {static void Main () {// Counter aCounter = new Counter (); // Error Counter. currentCount = 100; Counter. incrementCount (); Console. writeLine ("New count: {0}", Counter. currentCount); Console. writeLine ("Press any key Exit. "); Console. read key () ;}} copy code Note: If you uncomment the following statement in this example, it generates an error because the constructor is not accessible due to its protection level: // Counter aCounter = new Counter (); // Error static constructor is used to initialize any static data, or to execute a specific operation that only needs to be executed once. The static constructor is automatically called before the first instance is created or any static member is referenced. Copy the code class SimpleClass {static readonly long baseline; static SimpleClass () {baseline = DateTime. now. ticks ;}} the copy code static constructor has the following features: the static constructor neither has an access modifier nor a parameter. Before creating the first instance or referencing any static member, the class is automatically initialized by calling the static constructor. Static constructor cannot be called directly. In a program, you cannot control when to execute static constructors. A typical use of a static constructor is to use this constructor to write entries to a log file when the class uses a log file. Static constructor is also useful when creating packaging classes for unmanaged code. In this case, the constructor can call the LoadLibrary method. If a static constructor causes an exception, the constructor will not be called again at runtime, And the type remains uninitialized during the lifetime of the application domain where the program runs.

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.