c# 中 const 与 readonly 关键字看似相同,实则不同。重点在于确定值的时间。

const

const 很简单,就是一个常量,不可以被 static 修饰,因为被 const 修饰的字段自动成为静态字段,其值是在编译时可以确定的。

readonly

readonly 可以修饰实例字段(不被 static 修饰的字段),也可以修饰静态字段(被 static 修饰的字段)。意指为“只读”。其值确定的时间在类的构造函数中。

总结

关键字 确定值的时机
const 编译时
readonly 调用构造函数时

相关文章:

  • 2022-12-23
  • 2021-11-15
  • 2021-10-20
  • 2021-10-22
猜你喜欢
  • 2021-11-30
  • 2021-10-29
  • 2021-07-12
  • 2022-12-23
  • 2021-07-08
  • 2021-08-04
相关资源
相似解决方案