Const与static readonly的区别

在开发过程中,经常用到Const和static readonly,这两个用法很像,一直以来没有彻底的去了解这两个,今天来做个总结

本质区别:

  Const是在编译期间确定的,只能在申明时,通过常量赋值。

  static readonly是在运行时确定的,可以通过构造函数来赋值。

 

1     public class MyClass
2     {
3         public static readonly string Name = "Maple";
4         public const string Address = "HuBeiWuHan";
5 
6         public static readonly MyClass classTest = new MyClass();
7         public const MyClass classTest1 = new MyClass();
8     }

上面代码中第八行编译报错。报错信息:A const field of a reference type other than string can only be initialized with null

再举一个很明显的例子:

    public class MyClass1
    {
        public static readonly DateTime now = DateTime.Now;  //编译通过
        public const DateTime nowTime = DateTime.Now;    //编译出错 :'System.DateTime' cannot be declared const
    }

所以,针对const,必须给一个确定的值。 而static readonly,可以在运行期间,对其初始化。

 

posted on 2014-02-18 14:03  每次取名字都好难  阅读(489)  评论(0编辑  收藏  举报