A constructor is a method of a class that is the same as the class name and, if there is no explicit declaration, automatically generates a constructor that takes no arguments without executing any action when the system compiles.
However, if the constructor is explicitly declared, the system is not generated automatically. If the declared constructor is a constructor with parameters, we must instantiate the class with the constructor when instantiating the class. Look at the following code:
using System;
namespace gosoa.com.cn
{
public class test
{
public int num;
public test (int i)
{
this.num=i+5;
}
static void Main()
{
test classOne=new test(10);
int x=classOne.num;
Console.WriteLine(x);
}
}
}
As on the code, when instantiating the class, Test classone=new Test (10); A parameter was passed. If we test classone=new test (), and then instantiate the class, we will have an error. Because we explicitly declare a constructor with a parameter, when new test () is instantiated, the parameterless constructor is invoked, but there is no parameterless constructor in the class.
Let's take a look at the static constructor again.
In C # We can define an parameterless static constructor for a class (note that there must be no parameters), as long as the object of the class is created and the method executes. The function executes only once, and executes before the code references the class.
In general, there are static fields or properties in the class, and you need to initialize the static fields and properties from an external data source before you use the class for the first time, and then we use the static constructor to solve them.
The static constructor does not have an access modifier and other C # code does not call it, and it is always called by the. NET runtime when the class is loaded. A class can have only one static constructor.
Note that an instance constructor with no parameters can coexist with a static constructor in a class. Because the static constructor executes when the class is loaded, and the instance constructor executes when the instance is created, the two do not conflict.