Const vs. Readonly

时间:2021-08-15 16:37:55

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