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?
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:
If the value will never change, then const is fine - Zero
etc make reasonable consts ;-p Other than that, static properties are more common.
I would use static readonly
if the Consumer is in a different assembly. Having the const
and the Consumer in two different assemblies is a nice way to shoot yourself in the foot.
Some other things
const int a
readonly int a
上一篇: 从.net中的app.config或web.config中读取设置
下一篇: 静态只读与常量