Effective C#阅读笔记-2.使用readonly而不是const变量

readonly常量为运行时常量,const常量为编译时常量;编译时常量会在编译时,所有引用编译时常量的地方都会被替换为编译时常量的值,(编译时常量只能用于numbers 和strings, enums类型);运行时常量的值是在运行时确定的。当你引用一个只读常量时(read-only)IL会为你引用一个运行时常量的变量,而不是直接使用该值,可以是任何类型。

使用编译是常量的限制:编译时常量只能用于numbers 和strings, enums类型(primitive types ),因为只有这些类型才能在编译为IL时替换为字符value。不能使用new 来初始化一个编译时常量即使,这个常量是一个primitive types;相反运行是常量可以为任何类型,运行时常量可以使用初始化构造器赋值或者在类构造函数赋值,在其他地方不允许修改运行时常量,编译会无法通过。

1.编译时常量,申明时就是静态常量,可以通过类直接访问;运行时常量可以申明为实例常量;

 class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(ConstClass.EMD);
        }
        class ConstClass
        {
            public const int EMD = 2004;
        }
    }

2.运行时常量,引用的是变量,而不是变量的值,编译时常量正好想法,会在编译时用值替换。如果一个assemble a中引用的另外一个assemble b中的编译时常量,正好 assemble b编译时常量发生了改变,重新编译了,assemble a程序集没有重新编译,会出现不一致,可能会导致严重后果;

3.编译时常量带来的是性能的提升,运行时常量带来的是灵活性;

The final advantage of using const over readonly is performance: Known constant values can generate slightly more efficient code than the variable accesses necessary for readonly values. However, any gains are slight and should be weighed against the decreased flexibility. Be sure to profile performance differences before giving up the flexibility.

4.几个场景是必须使用编译时常量的,编译时需要访问的变量值;属性的参数;enum定义;

const must be used when the value must be available at compile times: attribute parameters and enum definitions, and those rare times when you mean to define a value that does not change from release to release. For everything else, prefer the increased flexibility of readonly constants.


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值