C # Const difference with the static readonly

Preface:

Const readonly and we should have used, we only know this much like the keyword, type of access is through, and are read in the program, but very few people can distinguish two different, today we go into the details Const and readonly.

Const:

The compiler by the const substituted with the value of its variables, the compiler knows the value of the constant. When modifying variables have to assign const, it must have been clear at compile time and constant

readonly

A read only field can be specified by the constructor during operation, it may not be assigned during initialization.

static  void the Main ( String [] args) 
{ 
          the Test Test = new new the Test ();
             // constructor run once (because static constructors) 
            test2 = the Test new new the Test (); 
            Console.WriteLine ( " End ---- - " ); 
} 
 public  class the Test 
    { 
        static  Readonly  int A = B * 10 ;
         static  Readonly  int B = 10 ;
         static  Readonly  int A1 = 10;
        static readonly int B1 = A1 * 10;
        const int C = D * 10;
        const int D =10;
        const int C1 = 10;
        const int D1 = 10 * C1;
        static Test()
        {
            A = 4;
           
            Console.WriteLine("A is {0},B is {1} ", A, B);
            //A is 0,B is 10
            Console.WriteLine("A1 is {0},B1 is {1} ", A1, B1);
            //A1 is 10,B1 is 100

            Console.WriteLine("C is {0},D is {1} ", C, D);
            //C is 100,D is 10 
            Console.WriteLine("C1 is {0},D1 is {1} ", C1, D1);
            //C is 10,D is 100 
        }
    }

 

 

Static const

Guess you like

Origin www.cnblogs.com/topsyuan/p/11209064.html