问题描述
我已经阅读了大约 const
和静态只读
字段。我们有一些仅包含常量值的类。它们用于我们系统中的各种事物。因此,我想知道我的观察是否正确:
I've read around about const
and static readonly
fields. We have some classes which contain only constant values. They are used for various things around in our system. So I am wondering if my observation is correct:
对于所有公开的东西,这些常量值是否总是 static readonly
?并且仅对内部/受保护/私有值使用 const
?
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
值直接刻录到调用中-现场;这是双刃的:
const
values are burned directly into the call-site; this is double edged:
- 如果在运行时获取值(可能是从config
- 如果更改const的值,则需要重建所有客户端
- 但是它可以更快,因为它避免了方法调用...
- ... JIT有时可能会内联
- 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
如果该值从不进行更改,则使用const就可以了- 0
等使之成为合理的const; p除此之外, static
属性是更常见。
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”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!