Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
401 views
in Technique[技术] by (71.8m points)

c# - 静态只读与常量(Static readonly vs const)

I've read around about const and static readonly fields.

(我已经阅读了有关conststatic readonly字段的信息。)

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?

(这些常量值是否应该对所有公共内容始终保持static readonly ?)

And only use const for internal/protected/private values?

(并且仅将const用于内部/受保护/私有值吗?)

What do you recommend?

(您有什么推荐的吗?)

Should I maybe even not use static readonly fields, but rather use properties maybe?

(我是否应该甚至不使用static readonly字段,而应该使用属性?)

  ask by Svish translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

public static readonly fields are a little unusual;

(public static readonly字段有点不寻常;)

public static properties (with only a get ) would be more common (perhaps backed by a private static readonly field).

(public static属性(只有get )会更常见(可能由private static readonly字段支持)。)

const values are burned directly into the call-site;

(const值直接刻录到调用站点中;)

this is double edged:

(这是双刃的:)

  • it is useless if the value is fetched at runtime, perhaps from config

    (如果在运行时获取值(可能是从config中获取)是没有用的)

  • if you change the value of a const, you need to rebuild all the clients

    (如果更改const的值,则需要重建所有客户端)

  • but it can be faster, as it avoids a method call...

    (但它可以更快,因为它避免了方法调用...)

  • ...which might sometimes have been inlined by the JIT anyway

    (... JIT有时可能内联了)

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很好- Zero等可以使const变得合理; p除此之外, static属性更为常见。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...