运行时常量优于编译时常量

      原创:

      C#语言有两种常量机制:一种为编译时常量,用const关键字来声明;一种为运行时常量,用readonly来声明。

      两种常量的差别是:编译时常量值的辨析发生在编译时,而运行时常量值的辨析发生在运行时。换言之,使用编译时常量编译后的IL代码直接引用它的值,而运行时常量编译后的IL代码引用的是readonly变量。

     那么这种差异对我们的程序将会带来什么影响呢?假设我们在一个名为ClassLibrary1的程序集中有一个类叫Customer的定义了一个const常量:

     public class Customer
    {
        public const int count = 10;   
    }

     在另外一个程序集WindowsFormsApplication1中引用了这个常量:

     textBox1.Text = Customer.count.ToString();

     假设随着时间的推移,我们又发布了一个新版的ClassLibrary1程序集:

    public class Customer
    {
        public const int count =
100;   
    }

      我们将新版的ClassLibrary1程序集发布出去,但是没有重新编译WindowsFormsApplication1程序集,运行WindowsFormsApplication1程序,可以看到在textBox1中的值还是10,并不是我们期望的100。

      如果我们将常量定义为如下形式:

    public class Customer
    {
        public
static readonly int count = 10;
    }

    新版的ClassLibrary1程序集相应改成如下:

    public class Customer
    {
        public static readonly int count = 100;
    }

     当我们发布新版的ClassLibrary1程序集,且没有重新编译WindowsFormsApplication1程序集时,运行的结果就是我们期望的结果100了。

    综上所述,只有当某些情况要求变量的值必须在编译时可用,才应该考虑使用const,例如:某些不随组件版本变化而改变的值。否则,我们应该优先使用readonly常量,从而获得其所具有的灵活性。

posted @ 2009-06-02 16:05  GIS一颗星  阅读(159)  评论(0)    收藏  举报