Article by: http://www.cnblogs.com/top5/archive/2009/10/31/1593706.html
The instance constructor is the instance constructor, And the Type constructor is the static constructor.
(1) In the instance constructor, We can initialize the instance fields and static fields of the class.
Public class Test
{
Private int m;
Private static int n;
Public Test ()
{
M = 1; // equivalent to this. m = 1;
N = 2; // The access between the instance field and the static field is no different.
}
}
(2) In the Type constructor, we can only initialize static fields for the purpose.
Public class Test
{
Private static int n = 1;
Static Test ()
{
N = 2;
// Is the final value of n 1 or 2? The sequence is first initialized to 1, and then assigned to 2 by the Type constructor.
}
}
(3) The conditions triggered by the instance constructor and the Type constructor are different.
The instance constructor is called when an instance of a class is constructed. The Type constructor is called when the class is accessed for the first time.
So it can be said that if an instance constructor of a class is called, its Type constructor will certainly be called (if any), and vice versa.
Public class Test
{
Public static int m;
Public Test ()
{
Console. WriteLine ("instance constructor ");
}
Static Test ()
{
Console. WriteLine ("Type constructor ");
}
}
Public class App
{
Static void Main ()
{
Test. m = 1;
// At this time, the Test class is accessed for the first time, so the Type constructor is called. The output result is: "Type constructor"
Test test = new Test ();
// At this time, the Test class is not accessed for the first time, but an instance of the class is created, so the output result is: "instance constructor"
// If the first line of code above is removed, you should know the output result. Please practice it yourself. Well, it's better to use "# Develop!
}
}