I went through the corresponding section of the C # Language Spec (v5.0), but I cannot find the part related to what I see.
If you have the code below, you will see the result below, which I expect:
using System; class Test { static int count = 0; static void Main() { Console.WriteLine("In Main(), AX=" + AX); } public static int F(string message) { Console.WriteLine(message); AX = ++count; Console.WriteLine("\tA.X has been set to " + AX); BY = ++count; Console.WriteLine("\tB.Y has been set to " + BY); return 999; } } class A { static A() { } public static int U = Test.F("Init AU"); public static int X = Test.F("Init AX"); } class B { static B() { } public static int R = Test.F("Init BR"); public static int Y = Test.F("Init BY"); }
Output:
Init AU AX has been set to 1 Init BR AX has been set to 3 BY has been set to 4 Init BY AX has been set to 5 BY has been set to 6 BY has been set to 2 Init AX AX has been set to 7 BY has been set to 8 In Main(), AX=999
This is exactly what I expect. In particular, note that even if the F () method is executed with the βInit AUβ parameter, it is called again (interrupted if you want) when a BY reference is encountered, which leads to the execution of the B initializers. When the B static constructor completes, we again return to the call to AU F (), which takes into account that BY is set to 6 and then to 2. Thus, we hope that this conclusion makes sense to everyone.
Here's what I don't understand: if you are commenting on the static constructor of B, this is the result you see:
Init BR AX has been set to 1 BY has been set to 2 Init BY AX has been set to 3 BY has been set to 4 Init AU AX has been set to 5 BY has been set to 6 Init AX AX has been set to 7 BY has been set to 8 In Main(), AX=999
Sections 10.5.5.1 and 10.12 of the C # specification (v5.0) indicate that the static constructor (and its static initializers) are executed when they refer to "any of the static members of the class." But here we have the AX referenced inside F (), and the static constructor is not running (since its static initializers do not work).
Since A has a static constructor, I would expect these initializers to start (and abort) the "Init BR" call to F (), just as B's static constructor is interrupted. The F () call in the "Init AU" call that I showed at the beginning.
Can anyone explain? Af has a meaning similar to a violation of the specification if there is no other part of the specification that allows it.
thanks
c # static static-initializer
Tom baxter
source share