When a field declaration contains
static
modifier, the field introduced by the declaration is a static field (static variable). When there is no
static
modifier, the field introduced by the declaration is an instance field (instance variable). A static field is not part of a particular instance; instead, it identifies only one storage location. No matter how many instances of a class are created, there is only one copy of the static field at any time for the associated application domain. Instance fields belong to an instance. Specifically, each instance of a class contains a separate collection of all the instance fields of the class.
(2)A field declaration can contain a variable initializer, which differs from the following: For a static field, a variable initializer is equivalent to an assignment statement that executes during class initialization. For instance fields, a variable initializer is equivalent to an assignment statement that executes when an instance of the class is created. Examples are as follows:
usingSystem;classtest{Static Doublex = Math.sqrt (2.0); inti = -; strings ="Hello"; Static voidMain () {Test a=NewTest (); Console.WriteLine ("x = {0}, I = {1}, S = {2}", X, A.I, A.S); }}
Generate output:
1.4142135623731 +, s = Hello
This is because the x
assignment to the pair occurs when the static field initializer executes, while the assignment to i
and s
is occurring when the instance field initializer executes.
(3) a static field variable initializer for a class corresponds to an assignment sequence, which executes in the order in which they appear in the associated class declaration. If a static constructor exists in the class, the execution of the static field initializer occurs before the static constructor is about to execute. Otherwise, a static field initializer is executed first before the static field of the class is used, but the actual execution time depends on the specific implementation.
The following example:
usingSystem;classtest{Static voidMain () {Console.WriteLine ("{0} {1}", B.y, a.x); } Public Static intFstrings) {Console.WriteLine (s); return 1; }}classa{ Public Static intX = TEST.F ("Init A");}classb{ Public Static intY = TEST.F ("Init B");}
or generate output
Static field initialization of C #