Class constructor
See
Three types of constructor:
Type annotations of class constructors are used to create and initialize an instance of classes. Special type instance constructor that is unacceptable outside the class. Unable to instantiate the class with a private constructor. This constructor will automatically call this constructor to initialize the class before creating the first instance or reference any static member. This constructor cannot be called directly.
I. Static constructor
Static constructor is used to initialize classes. The static constructor is automatically invoked to initialize the class before creating the first instance or reference any static member. The static constructor is declared by the following form:
[attributes] static identifier () {constructor-body}
among them:
Attributes (optional)
Additional declarative information. For more information on properties and attribute classes, see
C # properties.
Identifier
Identifier is the same as class name.
Constructor-body
A block containing the statement of the initialization class.
Note
The static constructor has neither accessing the modifier and there is no parameter.
The static constructor is automatically invoked to initialize the class before creating the first instance or reference any static member.
The static constructor cannot be invoked directly.
In the program, the user cannot control when to perform a static constructor.
Typical uses for static constructors are: When classifying log files, this constructor will be written to the log file.
Example
In this example, class Myclass has a static constructor and a static member mymethod (). When MYMETHOD () is called, the static constructor will be called to initialize the class.
// staticctor1.cs
Using system;
Class myclass
{
// static constructor:
Static myclass ()
{
Console.writeline ("The Static Constructor Invoked.");
}
Public static void mymethod ()
{
Console.writeline ("MyMethod Invoked.");
}
}
Class mainclass
{
Static void main ()
{
Myclass.mymethod ();
}
}
Output
The Static Constructor Invoked.
Mymethod invoked.
II. Private constructor private constructor is a special example constructor. It is usually used in classes that contain only static members. If the class has one or more private constructors without a public constructor, other classes are not allowed to create instances of this class (except for nested classes). For example: class nlog {// private constructor: private nlog () {}
Public Static Double E = 2.71828;} The declaration empty constructor prevents automatic generation of default constructor. Note that if you do not use access modifiers to constructor, it is still a private constructor by default. However, it is generally explicitly explicitly used to clearly indicate that the class cannot be instantiated. The private constructor can be used to block the creation class when there is no instance or instance method (such as a Math class) or the method to obtain an instance of the class. Example The following is an example of a class using a private constructor. // privatector1.csusing system;
Public class myclass {private myclass () {} public static int founder; public static int incry;}}
class MainClass {static void Main () {// If you uncomment the following statement, it will generate // an error because the constructor is inaccessible: // MyClass myObject = new MyClass (); // Error MyClass.counter = 100; Myclass.incrementCounter (); console.writeline ("new count: {0}", myclass.counter);}} Output NEW Count: 101 Note that if you cancel the following statement in this example, it will generate an error. Because this constructor is limited by its protection level, it is not accessible: // myclass myObject = new myclass (); // error instance constructor
The instance constructor is used to create and initialize the instance. The constructor is declared by the following form:
[attributes] [modifiers] Identifier ([FORMAL-parameter-list])
[Initializer] {constructor-body}
among them:
Attributes (optional)
Additional declarative information. For more information on properties and attribute classes, see
C # attribute
.
Modifiers (optional)
Allowed modifiers
Extern
And four
Access modifier
.
Identifier
Identifier is the same as class name.
FORMAL-parameter-list (optional)
The optional parameters passed to the constructor. The parameters must have the same access protection level as the constructor itself.
INITIALIZER
Call before performing a constructor. Initializer can be one of the following: one of the optional argument-list ::
Base
(argument-lis):
THIS
(argument-list)
Constructor-body
A block of the statement of the initialization class instance.
Note
Class constructor is called when creating a new object, for example:
Point mypoint = new point ();
A class can have multiple constructors. For example, a constructor without parameters can be declared (such as POINT ()) and a constructor with parameters (such as Point (INT X, INT Y)).
If the class does not construct a function, a default parameter constructor will be automatically generated and the object field is initialized using the default value (for example, INT will initialize 0). For more information on default, see the default table.
The class constructor can invoke the constructor of the base class by the initial value setting item, for example:
Public Cylinder (Double Radius, Double Height): Base (Radius, Height)
{
}
In the previous example, fields RADIUS and Height are initialized by the base class constructor. This is similar to the list of initialization of C .
The class constructor can also call another constructor of the same class via the keyword THIS, for example:
Public Point (): this (0,20)
{
}
In the previous example, the non-parameter constructor Point () calls another constructor with two parameters, initializing the default location to (0, 20). Example 1
The following example illustrates classes containing two class constructors: A class constructor has no parameters, and the other class constructor has two parameters.
// constructor1.cs
Using system;
Class Point
{
Public Int x, y;
// Default Constructionor:
Public Point ()
{
X = 0;
y = 0;
}
// a Constructor With Two Arguments:
Public Point (int x, int y)
{
THIS.X = X;
THIS.Y = Y;
}
// Override the Tostring Method:
Public override string toString ()
{
Return (String.Format ("({0}, {1})", x, y);
}
}
Class mainclass
{
Static void main ()
{
Point p1 = new point ();
Point p2 = new point (5, 3);
// Display the results using the overriden torstring method:
Console.writeline ("Point # 1 at {0}", P1);
Console.writeline ("Point # 2 at {0}", P2);
}
}
Output
Point # 1 at (0, 0)
Point # 2 at (5, 3)
Example 2
In this example, class Person does not have any constructor; in this case, the default constructor will be automatically provided while initializing the field to their default values.
// constructor2.cs
Using system;
Public Class Person
{
Public int Age;
Public String Name;
}
Public class mainclass
{
Static void main ()
{
Person P = New Person ();
Console.Write ("Name: {0}, Age: {1}", P.Name, P.AGE);
}
}
Output
Name :, agn: 0
Note that the default value of the AGE is 0, and the default value of Name is NULL. For more information on default, see the default table.
Example 3
The following example illustrates the use of the base class initial value setting item. The Circle class is derived from General class Shape, and the Cylinder class is derived from the Circle class. The constructor of each derived class uses the initial value setting item of its base class.
// CTORINIALIZER.CS
Using system;
Abstract Class Shape
{
Public const Double pi = math.pi;
Protected Double X, Y, Z;
Public Shape (Double X, Double Y, Double Z)
{
THIS.X = X;
THIS.Y = Y;
THIS.Z = z;
}
Public Abstract Double Area ();
}
Class Circle: Shape
{
Public Circle (Double Radius): Base (Radius, 0, 0)
{
}
Public Override Double Area ()
{
Return pi * x * x;
}
}
Class Cylinder: Circle
{
Public Cylinder (Double Radius, Double Height): Base (RADIUS)
{
y = height;
}
Public Override Double Area ()
{
Return 2 * (Base.Area ()) 2 * pi * x * y;
}
}
Class testclass
{
Public static void main ()
{
Double Radius = 2.5, Height = 3.0;
Circle MyCircle = New Circle (RADIUS);
Cylinder mycylinder = new cylinder (radius, height);
Console.writeline ("Area of the circle = {0: f2}",
mycircle.area ());
Console.writeline ("Area of the cylinder = {0: f2}",
mycylinder.area ());
}
}
Output
Area of the circle = 19.63
Area of the cyline = 86.39