In-depth C # class methods,
Constructor example1:
Static void Main (string [] args) {SE engineer = new SE (); engineer. age = 25; enginner. name = "Aibian Cheng"; // omit other attribute assignment operation Console. writeLine (engineer. sayHi ());}
We know that we need to use the attributes and methods of the class. First, we need to instantiate the class and create the SE object through SE engineer = new SE (); In instance 1, this method for creating a class instance is called constructor,
In example 1, the constructor is called to create the SE object and assign one-to-one values to its attributes. If no value is assigned, the system assigns default values to each field of the class.
As shown in Example 1, the constructor of a class is a special method in the class, which has the following features:
Here:
During development, we generally do not need to call constructors other than Class instance initialization in the constructor.
No-argument Constructor
Syntax:
// Access modifier Class Name () {// method body}
Constructors with Parameters
Syntax:
// Access modifier Class Name (parameter list) {// method body}
Implicit Constructor
When we do not define a class constructor shown in the class, the system automatically implicitly defines a non-argument constructor without a method body. This is an implicit constructor, it is worth noting that the system will not define the implicit constructor of the class for us when we display the construction of the defined class.
Example:
Public Class SE {string id; string name; // public SE (string id, string name) {this. id = id; this. name = name ;}// public SE () {}// other code of the SE class is omitted without parameters}
From this code, we can see that there are two constructors in the SE class with the same method name but different number of parameters. This method is method overload.
From the above examples, we can summarize the features of method overloading.
Note that the method name is the same as the parameter-type table. The return values of myopia are of different types and cannot be called method overload,
Method overload example
Example:
Public static void Main(string [] args){ Console.WriteLine(8); Console.WriteLine("Hello");}
In example, we can see that the first WriteLine method accepts an int type parameter, and the second WriteLine method accepts a string type parameter. WriteLine () provides multiple overload methods to meet various requirements,