静态只读VS常量 [英] Static readonly vs const
问题描述
我已经约常量
和静态只读
阅读领域的周围。我们有一个包含唯一不变的值有一些类。用于各地的不同的东西在我们的系统。所以我想知道如果我的观察是正确的:
I've read around about const
and static readonly
fields. We have some classes which contains only constant values. Used for various things around in our system. So I am wondering if my observation is correct:
如果这几样常数值始终为静态只读
的一切,这是公开的吗?只有使用常量
内部/保护/私有值?
Should these kind of constant values always be static readonly
for everything that is public? And only use const
for internal/protected/private values?
你有什么建议?我应该甚至不使用静态只读
字段,而是可能使用属性?
What do you recommend? Should I maybe even not use static readonly
fields, but rather use properties maybe?
推荐答案
公共静态只读域是有点不寻常;公共静态属性(只有一个 GET
)是比较常见的(可能由私人静态只读领域的支持)。
Public static readonly fields are a little unusual; public static properties (with only a get
) would be more common (perhaps backed by a private static readonly field).
常数值被直接烧入呼叫现场;这是双刃剑:
Const values are burned directly into the call-site; this is double edged:
- 这是无用的,如果该值在运行时牵强,也许是从配置
- 如果你改变一个常量的值,则需要重建的所有客户端
- ,但它可以更快,因为它避免了一个方法调用...
- ...这可能有时已经由JIT内联反正
如果该值将绝不会变化,则常数是好的 - 零
等做出合理的consts ;-p除此之外,静态属性更常见。
If the value will never change, then const is fine - Zero
etc make reasonable consts ;-p Other than that, static properties are more common.
这篇关于静态只读VS常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!