When to initialize static variables in C #

Source: Internet
Author: User

Reference from http://blog.csdn.net/dql1982/archive/2007/12/04/1916559.aspx

 

The initial values of static field variables of the class correspond to a sequence of values, which are executed in the order of the text they appear in the relevant class declaration. If a static constructor exists in the class, the execution of the initial value setting item of the static field occurs before the execution of the static constructor. Otherwise, the initial value of the static field is executed before the first time the static field of the class is used, but the actual execution time depends on the specific implementation. In the following example:

Using System;
Class Test
... {
Static   Void Main () ... {
Console. writeline ("{0} {1}", B .y, a.x );
}
Public   Static   Int F ( String S) ... {
Console. writeline (s );
Return 1;
}
}
Class A
... {
Public Static IntX=Test. F ("Init");
}
Class B
... {
Public Static IntY=Test. F ("Init B");
} Or generate the following output: init
Init B
1 or generate the following output: init B
Init
1. This is because X And Y The execution sequence of the initial value setting items cannot be determined in advance, and both of the above two sequences may occur. The only thing that can be determined is that they will certainly occur before those fields are referenced. However, the following example: Using System;
Class Test
... {
Static   Void Main () ... {
Console. writeline ("{0} {1}", B .y, a.x );
}
Public   Static   Int F ( String S) ... {
Console. writeline (s );
Return 1;
}
}
Class A
... {
Static A () ... {}
Public   Static   Int X = Test. F ( " Init " );
}
Class B
... {
Static B () ... {}
Public   Static   Int Y = Test. F ( " Init B " );
}
The output must be: init B
Init
1 1

This is because the rule about when to execute a static ConstructorRules:BStatic Constructor(AndBTo set the initial values of static fields.)Must be inABefore the static constructor and field initial value setting.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.