Think about the output results of the three-segment program below the limit:
Using System;
Public class Type1
...{
Public static int I;
Static Type1 () // explicitly defines the static Constructor
...{
Console. WriteLine ("Explicit: In Type1 Class Constructor ");
I = 1;
}
}
Public class Type2
...{
Public static int I = Init (2); // a static constructor is implicitly created by the CSC compiler during compilation.
Public static int Init (int j)
...{
Console. WriteLine ("Implicit: In Type2 Class Constructor ");
Return j;
}
}
Public class MainClass
...{
Static void Main ()
...{
// Use the Main function in the following three cases to guess the output result :)
}
}
1. The program has access to static members:
Static void Main ()
...{
Console. WriteLine ("In Main Function ");
Console. WriteLine (Type1. I );
Console. WriteLine (Type2. I );
}
2. The program does not access static members, but there are instance members in the class declared by the Access static members:
Static void Main ()
...{
Console. WriteLine ("In Main Function ");
Type1 t1 = new Type1 ();
Type2 t2 = new Type2 ();
}
3. Neither access static members nor access instance members
Static void Main ()
...{
Console. WriteLine ("In Main Function ");
}
In Case 1, the compilation and running results are output as follows:
E: CSC> csc staticfield. cs
Microsoft (R) Visual C #2005 compiler version 8.00.50727.42
For Microsoft (R) Windows (R) 2005 Framework 2.0.50727
Copyright (C) Microsoft Corporation 2001-2005. All rights reserved.
E: CSC> staticfield.exe
Implicit: In Type2 Class Constructor
In Main Function
Explicit: In Type1 Class Constructor
1
2
In Case 2, the output result is:
E: CSC> staticfield.exe
Implicit: In Type2 Class Constructor
In Main Function
Explicit: In Type1 Class Constructor
In case 3, the output result is:
E: CSC> staticfield.exe
In Main Function
Is the result different from what we imagined? Pai_^
Based on the above three tests, we can draw the following conclusions (for scenarios where static fields are defined in the class ):
If (if a static constructor is explicitly defined for the class, such as Type1 above)
{
If (any static or instance Member accessing this class in the Program)
{
After entering the Main function, call the static constructor before accessing any static or instance members defined in this class for the first time;
The static constructor will not be called in the future. The same static constructor can be called only once at most!
}
Else
{
The program does not call the static constructor of this class;
}
Else
{
If (any static or instance Member accessing this class in the Program)
{
Call the static constructor before executing the code in the Main function;
The static constructor will not be called in the future. The same static constructor can be called only once at most!
}
Else
{
The program does not call the static constructor of this class;
}
}