6 区别readonly和const

const是编译常量(即在编译期间就被解析,故效率高一点),readonly是运行时常量;

const修饰的常量在声明的时候必须初始化;readonly修饰的常量则可以在构造函数初始化与修改(故灵活一点);

        static readonly int A = B * 10;
        static readonly int B = 10;
        public static void Main(string[] args)
        {
            Console.WriteLine("A is {0},B is {1} ", A, B);
        }

 

        const int A = B * 10;
        const int B = 10;
        public static void Main(string[] args)
        {
            Console.WriteLine("A is {0},B is {1} ", A, B);
        }

 

  IL_0000:  nop
  IL_0001:  ldstr      "A is {0},B is {1} "
  IL_0006:  ldsfld     int32 ConsoleApp.Program::A
  IL_000b:  box        [mscorlib]System.Int32
  IL_0010:  ldsfld     int32 ConsoleApp.Program::B
  IL_0015:  box        [mscorlib]System.Int32
  IL_001a:  call       void [mscorlib]System.Console::WriteLine(string,
                                                                object,
                                                                object)

 

  IL_0000:  nop
  IL_0001:  ldstr      "A is {0},B is {1} "
  IL_0006:  ldc.i4.s   100
  IL_0008:  box        [mscorlib]System.Int32
  IL_000d:  ldc.i4.s   10
  IL_000f:  box        [mscorlib]System.Int32
  IL_0014:  call       void [mscorlib]System.Console::WriteLine(string,
                                                                object,
                                                                object)

 

posted @ 2016-01-12 17:31  小-黑  阅读(117)  评论(0)    收藏  举报