Class (1)-constructors

Source: Internet
Author: User

The most basic function of a constructor is to assign an initial value to all the fields and properties in a new instance of the type. So, according to its function, he doesn't need (and doesn't make sense) the return value. His function name must be the same as the class name.

Constructors for reference types

Whenever you create an instance of a class or struct, you call its constructor. A class or struct may have multiple constructors that accept different parameters. Constructors allow programmers to set default values, restrict instantiation, and write code that is flexible and readable.

If you do not provide a constructor for an object, by default C # Creates a constructor that does not have any arguments, and the constructor will call the parameterless constructor of its base class . If the base class does not follow up until the public constructor of object, he does nothing. (usually for all value types, go back to the corresponding type under System.ValueType such as Int32, and then assign 0 to the value type, and null for all reference types)

If we explicitly write out any of the constructors (with or without input parameters),C # will no longer create a constructor for us that has no parameters .

Constructors cannot be inherited. You cannot add abstract, virtual, new, sealed,override in front of the constructor.

Constructors are methods, so you can also have access modifiers. In general, constructors are public. But if we set it to private, then he cannot be accessed externally. The result is that the class cannot be instantiated. A private constructor is a special instance constructor. It is typically used in classes that contain only static members. If a class has one or more private constructors and no public constructors, other classes (except nested classes) cannot create instances of the class.

The constructor can be called from the default constructor (the one with no parameters). In general, if you do this (build a constructor chain), the default constructor can only have one, and his parameters are not limited. But only one reason is that all constructors must have the same name, so if more than one, this will not know which to call.

Base keyword

subclasses do not explicitly call the parent class's constructor, and the compiler automatically calls the parent class's default (no argument) constructor. You can use the Base keyword to indicate which constructor of the parent class you want to invoke.

Exercise: What does the following code output?

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.writel        INE ("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 the MYOBJ1, automatically call the parent class (and then the System.Object, whose constructors do nothing, the same as) the parameterless constructor, and its own parameterless constructor.

Event2: Instantiates myObj2, automatically calls the parent class's parameterless constructor, and its own parameter constructor.

Event3: Instantiate myObj3, according to the base keyword, explicitly call the parent class's parameter constructor, and its own parameter constructor.

Output:

In MyBaseClass ()

In Myderivedclass ()

In MyBaseClass ()

In Myderivedclass (4)

In MyBaseClass (4)

In Myderivedclass (4,int 8): Base (4)

Constructors for value types

A constructor for a value type can exist, but the system never calls automatically. We must explicitly call the constructor of the value type (for example, the struct's body). In addition , C # does not allow a parameterless constructor that defines a value type .

Static constructors

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

Assuming that there are several static fields in the class, in which we initialize their values, suppose we change the value of the static field in the external method, and then instantiate a new class, the value of the static field in the new class is reset to the initialized value, and if we do not want to do so but to keep the value of the static member unchanged, The use of static constructors is necessary. The static constructor executes only once (when the first instance of the type is created), and then no matter how many instances of that type are created again , this guarantees that the value of the static member in the type is not affected.

Static constructors have the following characteristics:

    1. Static constructors do not have access modifiers or parameters.
    2. The static constructor is called automatically to initialize a class before the first instance is created or any static members are referenced. This static constructor is executed only once.
    3. Parameterless constructors can coexist with static constructors. Although the parameter list is the same, one belongs to the class and one belongs to the instance, so there is no conflict.
    4. If a static constructor is not written, and the class contains a static member with an initial value set, the compiler automatically generates a default static constructor.
    5. The static constructor cannot be called directly.
    6. In a program, users cannot control when static constructors are executed.

The following example is selected from CLR via C #, what is the code output below?

classProgram {Static voidMain (string[] args) {b b=NewB ();        Console.readkey (); }    }    classA { PublicAstringtext)        {Console.WriteLine (text); }         }    classB {StaticA A1 =NewA"A1"); A A2=NewA"A2"); StaticB () {A1=NewA"A3"); }         PublicB () {A2=NewA"A4"); }    }

Answer:

A1

A3

A2

A4

Explanation: A2 and A4 must be better understood later, because the static constructor is executed before the other constructors. When creating an instance of a new B, the first thing to do is a static-related statement in the class and then a static constructor, so A1 prints before A3. The following example can be seen more clearly:

1     class Program2     {3         Static voidMain (string[] args)4         {5b b =NewB ();6 Console.readkey ();7         }8     }9 Ten     classA One     { A          PublicAstringtext) -         { - Console.WriteLine (text); the         }      -     } -  -     classB +     { -         StaticA A1 =NewA"A1"); +         Static intAproperty =1; A         intBproperty =2; atA A2 =NewA"A2"); -  -         StaticB () -         { -A1 =NewA"A3"); -         } in  -          PublicB () to         { +A2 =NewA"A4"); -         } the}

If we turn on debug mode, then the code (by line number) will run in the order starting with line 19, Then 20-13 to 15-21-(and not run non-static portions) 25-26-27-13 to 15-28 (static partial end) -22-23-13 to 15-31-32-13 to 15-33-6-end.

A static constructor executes only the statements in the class that are related to the static (first initialize the variables in the class and statically, and then execute the static function statements). The static constructor is executed only once . The execution of a static constructor is preceded by the initialization of the type.

What does the following code output?

1  Public classA2     {3          Public Static ReadOnly intx;4         StaticA ()5         {6x = B.y +1;7         }8     }9 Ten     classB One     { A          Public Static inty = a.x +1; -  -         Static voidMain (string[] args) the         { -Console.WriteLine ("X:{0},y:{1}. ", a.x, y); - console.readline (); -         } +}

This problem is very strange, at first glance seems unable to run, let us analyze slowly. First the program runs from Class B, and then the program discovers that Class B has a static member Y, initializes it without a static constructor, and initializes it to 0 first. (You can split line 12th into two lines, the first line is public static int y, the second line is y = a.x + 1). At this time y=0, and then make y equals a.x+1, the program does not know what a is, so enter a class, initialize a static member X is 0, and then execute a static constructor, at this time because the B.Y is 0, so you can successfully set X to 0+1=1.

At this time the program left Class A, back to line 12th, y=1+1=2, finally, print out the results, x=1,y=2.

Class (1)-constructors

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.