C#中const 和 static readonly 区别及应用

简述:

const

用 const 修饰符声明的成员叫常量,是在编译期初始化并嵌入到客户端程序。程序在运行之前就编译好了,不能修改。.

static readonly

用 static readonly 修饰符声明的成员依然是变量,只不过具有和常量类似的使用方法:通过类进行访问、初始化后不可以修改。

区别是:const编译初始化就产生了,static readonly 是在运行初期初始化。

使用示例

测试类:

using System;using System.Collections.Generic;using System.Text; namespace Example02Lib{    public class Class1    {        public const String strConst = "Const";        public static readonly String strStaticReadonly = "StaticReadonly";        //public const String strConst = "Const Changed";        //public static readonly String strStaticReadonly = "StaticReadonly Changed";    }}
调用代码:
using System;using System.Collections.Generic;using System.Text;using Example02Lib; namespace Example02{    class Program    {        static void Main(string[] args)        {            //修改Example02中Class1的strConst初始值后,只编译Example02Lib项目            //然后到资源管理器里把新编译的Example02Lib.dll拷贝Example02.exe所在的目录,执行Example02.exe            //切不可在IDE里直接调试运行因为这会重新编译整个解决方案!!            //可以看到strConst的输出没有改变,而strStaticReadonly的输出已经改变            //表明Const变量是在编译期初始化并嵌入到客户端程序,而StaticReadonly是在运行时初始化的            Console.WriteLine("strConst : {0}", Class1.strConst);            Console.WriteLine("strStaticReadonly : {0}", Class1.strStaticReadonly);            Console.ReadLine();        }    }} 

结果:
strConst : Const
strStaticReadonly : StaticReadonly

修改后的示例:

我们重新赋值后再次运行,看如下效果。

测试类:

using System;using System.Collections.Generic;using System.Text; namespace Example02Lib{    public class Class1    {        //public const String strConst = "Const";        //public static readonly String strStaticReadonly = "StaticReadonly";        public const String strConst = "Const Changed";        public static readonly String strStaticReadonly = "StaticReadonly Changed";    }}

结果

strConst : Const
strStaticReadonly : StaticReadonly Changed