Class (1)-constructor, constructor

Source: Internet
Author: User

Class (1)-constructor, constructor

The most basic function of the constructor is to assign an initial value to all fields and attributes of a new instance of the type. Therefore, according to its function, it does not need (or make no sense) the return value. The function name must be the same as the class name.

Constructor of reference type

At any time, as long as you create an instance of a class or structure, it will call its constructor. Classes or structures may have multiple constructors that accept different parameters. Constructors allow programmers to set default values, restrict instantiation, and write flexible and easy-to-read code.

If no constructor is provided for an object, C # creates a constructor without any parameters by default.It will call the non-parameter constructor of its base class.. If the base class does not exist, it will continue to be traced until the object's public constructor does nothing. (Generally, all value types are traced back to the corresponding types under system. valuetype, such as int32, and then 0 is assigned to the value type. For all reference types, null is assigned)

If we explicitly write any Constructor (whether input or not ),C # will not create the constructor without parameters for us anymore..

Constructors cannot be inherited. Abstract, virtual, new, sealed, and override cannot be added before the constructor.

Constructors are methods, so they can also have access modifiers. In general, constructors are all PUBLIC. However, if we set it to PRIVATE (PRIVATE constructor), it cannot be accessed externally. The result is that the class cannot be instantiated. A 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.

Between constructors, you can use this to call the default constructor (the one without parameters ). Generally, if you do this (build a constructor chain), only one constructor can be created by default, and its parameters are not limited. However, one reason is that all constructors must have the same name. Therefore, if more than one constructor name is exceeded, this does not know which one to call.

Base keyword

If the subclass does not explicitly call the constructor of the parent class, the compiler automatically calls the default (No parameter) constructor of the parent class.AvailableBaseKeyword indicates which constructor of the parent class to call.

Exercise: What is the output of the following code?

public class MyBaseClass    {        public MyBaseClass()        {            Console.WriteLine("In MyBaseClass()");        }        public MyBaseClass(int i)        {            Console.WriteLine("In MyBaseClass(" + i + ")");        }    }    public class MyDerivedClass : MyBaseClass    {        public MyDerivedClass()        {            Console.WriteLine("In MyDerivedClass()");        }        public MyDerivedClass(int i)        {            Console.WriteLine("In MyDerivedClass(" + i + ")");        }        //public MyDerivedClass(int i, int j)        //{        //    Console.WriteLine("In MyDerivedClass(int i,int j)");        //}        public MyDerivedClass(int i, int j) : base(i)        {            Console.WriteLine("In MyDerivedClass(" + i + ",int " + j+ "):base(" + i + ")");        }    }    class Program    {        static void Main(string[] args)        {            //Event1            MyDerivedClass myObj1 = new MyDerivedClass();            Console.WriteLine();            //Event2            MyDerivedClass myObj2 = new MyDerivedClass(4);            Console.WriteLine();            //Event3            MyDerivedClass myObj3 = new MyDerivedClass(4,8);            Console.WriteLine();            Console.ReadKey();        }    }

 

Answer:

Event1: instantiate myObj1 and automatically call the non-parameter constructor of the parent class (which is system. object at the top, and its constructor does nothing, the same below) and its own non-parameter constructor.

Event2: instantiate myObj2 and automatically call the non-argument constructor of the parent class and its own constructor.

Event3: instantiate myObj3. Based on the base keyword, it explicitly calls the parameter constructors of the parent class and its own parameter constructors.

Output:

In MyBaseClass ()

In MyDerivedClass ()

In MyBaseClass ()

In MyDerivedClass (4)

In MyBaseClass (4)

In MyDerivedClass (4, int 8): base (4)

Constructor of Value Type

A constructor of the value type can exist, but the system will never automatically call it. We must explicitly call a Value Type constructor (such as a struct ). In addition, C # The non-parameter constructor that does not allow defining value types.

 

Static Constructor

For non-static fields of the type, each object of the type maintains an independent copy of the field.For static fields, all instances of this type share a value.. If you want to define a data point that all objects can share, you can consider using static members.

Suppose there are several static fields in the class. In the constructor, We initialize their values. In this case, we assume that we have changed the value of the static field in the external method, then instantiate a new class. The value of the static field in the new class will be reset to the initial value. If we do not want this, we need to keep the value of the static member unchanged, static constructor is required.The static constructor will only run once (when the first instance of this type is created). After that, no matter how many instances of this type are created, it will not run again.This ensures that the values of static members in the type are not affected.

Static constructors have the following features:

The following example is selected from CLR via c #. What is the output of the following code?

class Program    {        static void Main(string[] args)        {            B b = new B();            Console.ReadKey();        }    }    class A    {        public A(string text)        {            Console.WriteLine(text);        }         }    class B    {        static A a1 = new A("a1");        A a2 = new A("a2");        static B()        {            a1 = new A("a3");        }        public B()        {            a2 = new A("a4");        }    }

Answer:

A1

A3

A2

A4

Explanation: a2 and a4 must be well understood later, because static constructors are executed before other constructors. When creating a new B instance, the first statement in the class is related to static, and then the static constructor, so a1 is printed before a3. The following example shows more clearly:

 1     class Program 2     { 3         static void Main(string[] args) 4         { 5             B b = new B(); 6             Console.ReadKey(); 7         } 8     } 9 10     class A11     {12         public A(string text)13         {14             Console.WriteLine(text);15         }     16     }17 18     class B19     {20         static A a1 = new A("a1");21         static int aProperty = 1;22         int bProperty = 2;23         A a2 = new A("a2");24 25         static B()26         {27             a1 = new A("a3");28         }29 30         public B()31         {32             a2 = new A("a4");33         }34     }

If we enable the debugging mode, the Code (by line number) will start from line 19 and then 20-13 to 15-21-(non-static parts will not run) 25-26-27-13 to 15-28 (static part ended)-22-23-13 to 15-31-32-13 to 15-33-6-end.

The static constructor only executes the class andStatic-related statements (initialize static-related variables in the class before executing static function statements). Static ConstructorOnly once. The execution opportunity of the static constructor is to initialize this type.Before.

What is the output of the following code?

 1 public class A 2     { 3         public static readonly int x; 4         static A() 5         { 6             x = B.y + 1; 7         } 8     } 9 10     class B11     {12         public static int y = A.x + 1;13 14         static void Main(string[] args)15         {16             Console.WriteLine("x:{0},y:{1}。", A.x, y);17             Console.ReadLine();18         }19     }

This question is very strange. At first glance, it seems that it cannot be run. Let's analyze it slowly. First, the program starts to run from Class B. Then, the program finds that Class B has a static member y, Which is initialized without a static constructor. Therefore, it is initialized to 0 first. (You can split row 12th into two rows. The first row is public static int y, and the second row is y = A. x + 1 ). At this time, y = 0, and then make y equal to. x + 1, the program does not know what A is, so it enters Class A, initializes the static member x of A to 0, and then executes the static constructor of A, because B. y is 0, so we can smoothly set x to 0 + 1 = 1.

At this time, the program leaves Class A and returns to row 12th, where y = 1 + 1 = 2. Finally, the result is printed, x = 1, y = 2.

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.