1, what is the construction method?
First, it is a method, which is one of the many methods in a class. Second, it has some features that are not available in other methods in the class.
This method is executed at the beginning of the class execution.
2. How are the construction methods different from other methods?
Method Name: The ordinary method in the class can be named according to the code writer's personal preference . However, the construction method is not possible. The construction method must have the same name as the class name. In other words, when a method name in a class is the same as the class name, C # considers this method to be the constructor of the class.
Execution order: The normal method in a class is called after the class is instantiated, and the constructor is executed before the class is instantiated.
Circle Round Class
Using system;using system.collections.generic;using system.linq;using system.text;using System.Threading.Tasks; Namespace over{ class Circle {public int r; Public Circle ()//constructor with no arguments, for the default constructor method { Console.WriteLine ("The construction method of the Circle class is called"); R = Ten; } public Circle (int rid) { Console.WriteLine ("The constructed method overloaded in the Circle class is called"); r = RID; } public double s () { return Math.PI * R * r;}} }
In the absence of a constructor method, the default class will add a method with the same name and class name as the constructor method, which is called the construction methods without adding a key such as void, int, public+ the method name directly ()
Program Class
Using system;using system.collections.generic;using system.linq;using system.text;using System.Threading.Tasks; Namespace over{ class program { static void Main (string[] args) {program p = new program (); P.run (); } void Run () { Circle C; c = new Circle (); C = new Circle (20);//pass parameter 20 to the Circle class, calling the overloaded construction method with the int rid parameter double area = C.s (); Console.WriteLine (area); Console.readkey ();}}}
Instantiate a circle attribute of C,
Circle C = New Circle ();
In the case of non-transmitting value, the default is to use the construction method without parameters, and define the r=10;
In the execution
c = new Circle (20);
Pass parameter 20, which is called the overloaded public Circle (int rid) construction method, which is r=20;
C # Constructor Method overloading