Using System; Class P {static readonly int a=b*10; static readonly int b=10; public static void Main (string[] args) {Console.WriteLine ("A was {0},b is {1}", A, b); } }
For the above code, what is the output? A lot of people would think it was a 100,b is 10! In fact, the correct output result is A was 0,b is 10. Well, if you change to the following:
Using System; Class P {const int a=b*10; const int b=10; public static void Main (string[] args) {Console.WriteLine ("A was {0},b is {1}", A, b); } }
For the above code, how much output is the result? Is it 0,b is 10? In fact, it is wrong, this time the correct output is a was 100,b is 10.
So why is that so? In fact, the above said, const is a static constant, so at compile time will be a and B value down (that is, b variable 10, and a=b*10=10*10=100), then the output of the main function is of course A is 100,b is 10. The static readonly is a dynamic constant, the value of the variable is not parsed during compilation, so the start is the default value, like A and B are int type, ancient capital is 0. And in the execution of the program to A=B*10, so a=0*10=0, the program then executes to b=10 this sentence, only real B's initial value 10 is assigned to B.
【. NET pose with "const and readonly initialization posture