Const vs. Readonly

本文详细解析了C#中const与readonly关键字的使用区别,包括它们在初始化、赋值时机、静态与实例化变量的适用性等方面的差异。同时,文章还探讨了这两种关键字在运行效率与代码维护上的考量。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Const

  • 被const修饰的变量不能为静态,因为const实际隐式上已经是静态变量。
  • const变量在声明时就必须进行初始化,否则会有编译错误。
  • const变量的赋值是发生在编译期间

Readonly

  • readonly修饰的变量既可以是静态的,也可以是非静态的(实例化的)
  • readonly变量可以在声明时赋值,也可以在对应的构造函数中赋值(初始化),如果变量是静态的,可以在静态构造函数中初始化;如果是非静态的,则需要在实例构造函数中初始化
  • 因为上面的原因,所以readonly变量是在运行时才进行赋值的

Other Views

const = value assigned at Compile time and unchangeable once established.

readonly = value assigned at run time and unchangeable once established.

static readonly is typically used if the type of the field is not allowed in a const declaration, or when the value is not known at compile time.

Remember that for reference types, in both cases (static and instance) the readonly modifier only prevents you from assigning a new reference to the field.  It specifically does not make immutable the object pointed to by the reference.

If the value will never change, then const is fine - Zero etc make reasonable consts ;-p Other than that, static properties are more common.

Const values are burned directly into the call-site; this is double edged:

  • it is useless if the value is fetched at runtime, perhaps from config
  • if you change the value of a const, you need to rebuild all the clients
  • but it can be faster, as it avoids a method call...
  • ...which might sometimes have been inlined by the JIT anyway

If the value will never change, then const is fine - Zero etc make reasonable consts ;-p Other than that, static properties are more common.

References

 

转载于:https://www.cnblogs.com/EasonWu/p/const-vs-readonly.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值