[c#] const 与 readonly

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

const

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

readonly

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

总结

关键字 确定值的时机
const 编译时
readonly 调用构造函数时
posted @ 2016-11-02 22:04  endlesstravel  阅读(372)  评论(0编辑  收藏  举报