A detailed description of the C # class construction method and sample code

Source: Internet
Author: User
This article mainly introduces the construction method of C # class. Have a certain reference value, follow the small series below to see it





First, the construction method



The constructor of a class is one of the member methods of a class, and its purpose is to initialize the members of the class. The method of constructing a class is divided into:



1. Static Construction method



2. Example Construction methods



1. Static Construction method



The static construction method of a class is one of the member methods of a class, and its purpose is to initialize the static members of the class. Here's a look at the code example:


using System;
namespace LycheeTest {
  class Test {
  // Define a static member variable
  private static int a;
  // Define a static constructor
  static Test () {
   // Initialize static member variables
   a = 11;
  }
  public void Show () {
   Console.WriteLine ("The value of static field a is: {0}", a);
  }
  }
  class Program {
  static void Main (string [] args) {
   Test t = new Test ();
   t.Show ();
   Console.ReadKey ();
  }
  }
}


First, the above code defines two classes. The 3rd line of code defines the class Test. When defining a class, there are two access modifiers for the class, one is public and the other is internal. When no access modifier is written, the access rights of the class are internal by default. The meaning of this access is that the class can only be accessed by this assembly and cannot be accessed by a class other than this assembly. If the class belongs to a class library, it must be public, otherwise the assembly that calls it cannot access it. The 5th line of code defines a static field member, and the 7th line of code is a static construction method. As you can see, the static construction method is characterized by the static keyword that indicates that the method is statically, the method name is exactly the same as the class name, and the case is noted here. static construction methods cannot contain parameters, and static construction methods cannot have return values . The static constructor can be used to initialize static member operations. The 11th line of code defines an instance method that is used to output the value of a static field. In the 16th line of the class program, main (note: In Java is main) method called the class, line 18th creates an instance of this class, line 19th calls the class instance method.



As you can see from the code above, the static construction method of the class is not explicitly called.



Let's look at the results of the above code:



The value of static field a is: 11



As you can see, the static construction method is actually executed. The above example is one of the execution conditions of the static construction method, and the static constructor method of the class is automatically called when an instance of the class is created.



The call order of a static construction method is after the initializer for the static field.



The first step is to set the default value of the static field, the second step is to execute the initializer of the static field, and the third step is to invoke the static constructor of the class.



The following changes the previous code example, the code is as follows:


using System;
namespace LycheeTest {
  class Test {
  private static int a;
  static Test () {
   a ++;
  }
  public void Show () {
   Console.WriteLine ("The value of static field a is: {0}", a);
   14
  }
  }
  class Program {
  static void Main (string [] args) {
   Test t = new Test ();
   t.Show ();
   Test t1 = new Test ();
   t.Show ();
   Console.ReadKey ();
  }
  }
}


This code modifies the static construction method to make static field a self-increment in the method body. You then create an instance of the class in line 17th of the code, and then call the instance method of the class again.



Below are the results of the execution:


The value of the static field a is: 1
The value of the static field a is: 1


As you can see, the value of the static field does not increase. This is the characteristic of the static construction method execution, which executes only once. When the assembly runs, an application domain is created, and the static construction method of the class is executed only once in an application domain.



The following changes are made to the code instance as follows:


using System;
namespace LycheeTest {
  class Test {
  public static int a;
  static Test () {
   Console.WriteLine ("Static constructor of class begins execution");
   a ++;
  }
  public void Show () {
   Console.WriteLine ("The value of static field a is: {0}", a);
  }
  }
  class Program {
  static void Main (string [] args) {
   Console.WriteLine ("The value of static field a is: {0}", Test.a);
   Console.WriteLine ("The value of static field a is: {0}", Test.a);
   Console.ReadKey ();
  }
  }
}


This code prints out a line of markup in the static construction method of the class, and the access to the static field of the class is also modified to public, which allows it to be called outside the class. The value of the static field is printed two times in the Main method, note that the static field of the calling class outside the class needs to be referenced using the class name.



Here is the result of the code execution:


The static constructor of the class starts executing
The value of the static field a is: 1
The value of the static field a is: 1


This section of code does not create an instance of the class. The static constructor method of a class is called before a static member of the class is referenced. The static members of this called class include static fields and static methods. This is the second condition of the static constructor method invocation of the class.



The following changes are made to the code instance as follows:


using System;
namespace LycheeTest {
  class Program {
  private static int a;
  static Program () {
   Console.WriteLine ("Static constructor of class is called");
   a = 11;
  }
  static void Main (string [] args) {
   Console.WriteLine ("Main method is called");
   Console.WriteLine ("The value of static field a is: {0}", a);
   Console.ReadKey ();
  }
  }
}


This code defines static fields and static construction methods in the class that contains the Main method. Because the Main method is also a static method, the static constructor method of the class is called and it is the entry point method of the class, then who is the first call between the static constructor method and the class? Let's start with the result of the code execution:


The static constructor of the class is called
Main method is called
The value of static field a is: 11


As you can see from the execution of the code, because the class's entry point method is still a static method, the static constructor method is called first before any static members are called. Therefore, it can be concluded that the static construction method of a class is called before the Main method of the class.



Can the static construction method of a class be explicitly called? Here's a look at the code example:


using System;
namespace LycheeTest {
  class Program {
  private static int a;
  static Program () {
   Console.WriteLine ("Static constructor of class is called");
   a = 11;
  }
  static void Main (string [] args) {
   Program ();
   Console.ReadKey ();
  }
  }
}


In the 10th line of the code, the static construction method of the class is explicitly called, and the compiler will make an error.



2. Instance Constructors



An instance of a class is constructed as a method of a member of a class that initializes an instance member of the class. Instance construction methods can implement overloading, and when you create an instance of a class, you can explicitly specify different parameters to invoke the overloaded different instance construction methods. Here's a look at the code example:


using System;
namespace LycheeTest {
  class Program {
  private static int a;
  private int b = 12;
  private string c = "Hello World";
  static Program () {
   Console.WriteLine ("Static constructor of class is called");
   a = 11;
  }
  public Program (int a, string s) {
   Console.WriteLine ("Constructor with two parameters is called");
   this.b = a;
   this.c = s;
  }
  public Program (int a): this (a, "Invoke constructor via this keyword") {
   Console.WriteLine ("Constructor with one parameter is called");
  }
  public void Show () {
   Console.WriteLine ("The value of static field a is: {0}", a);
   Console.WriteLine ("The value of the instance field b is: {0}", b);
   Console.WriteLine ("The value of the instance field c is: {0}", c);
  }
  static void Main (string [] args) {
   Program p1 = new Program (33, "This is the created instance P1");
   Program p2 = new Program (34);
   p1.Show ();
   p2.Show ();
   Console.ReadKey ();
  }
  }


The 4th, 5th, and 6th lines of this code define three field members respectively, the 4th row is a static field, and the 5th line and the 6th Line code have initializers. The 8th line of code is the definition of an instance construction method, which is also named after the class name, which has no return value and is preceded by the access modifier, which can be used with the access modifier including public, private, and protected. The protected means that the construction method can only be accessed within this class. Instance construction methods can take parameters. The instance construction method of line 12th uses two incoming parameters to assign an instance field. The 17th line of code defines an instance construction method with one parameter, which forms an overload with the previous instance construction method. The instance construction method can call other instance construction methods through the This keyword, by using a colon after the argument list and then the This keyword, followed by the argument list, which matches another overloaded instance construction method. The 17th line is constructed with only one parameter, which passes this argument through the This keyword to another construction method, and at the same time, a string parameter is passed to it when another constructor method is called with this. The instance method of line 24th prints the value of the field member of the class. In the Main method, the 26th line of code and the 27th line of code define two instances, each of which uses the new keyword to invoke different instance construction methods. Lines 28th and 29th call the instance method to print the values of the class's static fields and the two field members of the instance, respectively.



Let's take a look at the results of the code:


The static constructor of the class is called The constructor with two parameters is called The constructor with two parameters is called The constructor with one parameter is called
The value of static field a is: 11
The value of the instance field b is: 33
The value of instance field c is: This is the created instance P1 The value of static field a is: 11
The value of the instance field b is: 34
The value of the instance field c is: the constructor is called with the this keyword


The execution of the instance construction method is now described by executing the result, and when the 26th line of code creates an instance of the class, the static field of the class is first set to the default value, because there is no initializer for the field, so the static construction method of the class is then executed. At this point the static field A is set to 11. Because the 26th line of code uses new to invoke an instance construction method with two arguments, first instance field B is set to 0, and instance field C is set to null. Then the initializer for the field is executed, and B is assigned the value 12,c is assigned to "Hello World". The next execution instance constructs the first statement in the method body, and the string "constructor with two arguments is called" is printed. The next instance of P1 's field B is set to the passed parameter 33, note that the constructor method's formal parameter a overrides the static field a of the class. That is, the local variable A that is working on the instance construction method. The instance field C is then set to the string "This is the instance created by P1". The 27th line of code uses the new keyword to invoke an instance construction method with a parameter, and when called, the instance field B that belongs to P2 first is set to 0 and the instance field C is set to null. Then the initializer for the field is executed, and B is assigned the value 12,c is assigned to "Hello World". The next step is to construct an instance of this reference with two arguments, and the string "constructor with two arguments is called" is printed. Then B is set to 34,c is set to "call construction method through this keyword". Finally, code control is returned to execute the print statement in the method body with an instance of a parameter, and the string "constructor with a parameter is called" is printed. At this point, the execution of the instance construction method is complete. The next code prints the values of the static fields, and you can see that the values of the static fields are the same for the two instances, but their instance fields have different values.



Optional parameters and named parameters can also be used for instance construction methods, as shown in the code example:


using System;
namespace LycheeTest {
  class Program {
  private int b;
  private string c;
  public Program (int a = 12, string s = "") {
   this.b = a;
   this.c = s;
  }
  public void Show () {
   Console.WriteLine ("The value of the instance field b is: {0}", b);
   Console.WriteLine ("The value of the instance field c is: {0}", c);
  }
  static void Main (string [] args) {
   Program p1 = new Program (); // Both parameters of the constructor take default values
   Program p2 = new Program (34); // The string type parameter of the constructor adopts the default value
   Program p3 = new Program (23, "Hello World"); // The two parameters of the constructor take the passed parameters
   Program p4 = new Program (s: "The weather is really good today"); // Use a named parameter, another parameter a uses the default value
   p1.Show ();
   p2.Show ();
   p3.Show ();
   p4.Show ();
   Console.ReadKey ();
  }
  }
} 


The 6th line of the code defines a construction method with optional parameters and named arguments, and then 15th creates an instance of a class that does not pass any parameters in the constructor, at which point the two parameters of the constructed method take the default values. The 16th line of code passed a parameter of type int to the construction method, and another parameter of type string takes the default value. The 17th line of code passed in two parameters, and the two parameters of the construction method used both of the passed arguments. The 18th line of code uses a named parameter to specify that the passed-in parameter is a string-type argument and passes it to the formal parameter s. At this point another parameter of type int takes the default value. Line 19th through line 23rd code prints the value of the instance field of the class. The result of this code execution is as follows:



 
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.