C# 什么时候,如果有的话,我们应该使用 const 吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/555534/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 08:01:20  来源:igfitidea点击:

When, if ever, should we use const?

c#constreadonly

提问by Frederick The Fool

Constis baked into the client code. Readonlyisn't. But constis faster. May be only slightly though.

Const被嵌入到客户端代码中。Readonly不是。但const速度更快。可能只是轻微的。

The question is, is there ever any scenario where you should prefer constover readonly? Or to rephrase, are we not practically alwaysbetter off using a readonlyinstead of a const(keeping in mind the above-said baking thing)?

现在的问题是,是否有过,你应该喜欢的任何场景constreadonly?或者换个说法,我们实际上是否总是最好使用 areadonly而不是 a const(记住上述烘焙的东西)?

采纳答案by Andrew Arnott

I believe the only time "const" is appropriate is when there is a spec that you're coding against that is more durable than the program you're writing. For instance, if you're implementing the HTTP protocol, having a const member for "GET" is appropriate because that will never change, and clients can certainly hard-code that into their compiled apps without worrying that you'll need to change the value later.

我相信“const”唯一合适的时间是当您编码的规范比您正在编写的程序更持久时。例如,如果您正在实现 HTTP 协议,那么为“GET”设置一个 const 成员是合适的,因为这永远不会改变,并且客户当然可以将其硬编码到他们编译的应用程序中,而不必担心您需要更改值后。

If there's any chance at all you need to change the value in future versions, don't use const.

如果您需要在将来的版本中更改该值,请不要使用 const。

Oh! And never assume const is faster than a readonly field unless you've measured it. There are JIT optimizations that may make it so it's actually exactly the same.

哦!并且永远不要假设 const 比只读字段快,除非你已经测量过它。有一些 JIT 优化可能会使其实际上完全相同。

回答by JoelFan

You should use const whenever you can set the value in the declaration and don't have to wait for the constructor.

只要可以在声明中设置值并且不必等待构造函数,就应该使用 const。

回答by shahkalpesh

readonly is useful when the initialization is not straight forward.
const can be used when you are sure of the value before it is compiled.

readonly 在初始化不直接时很有用。
当您在编译之前确定该值时,可以使用 const。

In a way, readonly is a runtime const & const is a compile time constant value.

在某种程度上, readonly 是运行时 const & const 是编译时常量值。

EDIT: If you look at some code using www.koders.com, you will find that there is a use of readonly where const could have been used. I think, the reason behind that could be it is modifiable in the constructor (if need be). In case of const (especially public), you have a chance of breaking the client code dependent on your code.

编辑:如果您使用 www.koders.com 查看一些代码,您会发现在可以使用 const 的地方使用了 readonly。我认为,这背后的原因可能是它在构造函数中是可修改的(如果需要的话)。在 const(尤其是公共)的情况下,您有机会破坏依赖于您的代码的客户端代码。

回答by ChrisW

You can use a const value as a case in a switch statement, fwiw.

您可以在 switch 语句 fwiw 中使用 const 值作为案例。

回答by Logan5

const cannot be used for classes or structures (except for string constants and null, as Mr. Skeet pointed out), only for value types and are accessed as static fields. A const's value is set at compile time and must be set when it is declared.

const 不能用于类或结构(除了字符串常量和 null,正如 Skeet 先生指出的那样),只能用于值类型并且作为静态字段访问。const 的值在编译时设置,并且必须在声明时设置。

readonly can be used for anything except enumerations and can be either a static or instance field. A readonly's value is set at runtime and can be set differently depending on which constructor is called.

readonly 可用于除枚举之外的任何内容,并且可以是静态或实例字段。readonly 的值是在运行时设置的,可以根据调用的构造函数进行不同的设置。

Here's a good pagefor an overview of the const, readonly and static keywords.

这是一个很好的页面,用于概述 const、readonly 和 static 关键字。

回答by cletus

Const vs readonly:

常量与只读

A quick synopsis on the differences between 'const' and 'readonly' in C#: 'const':

  • Can't be static.
  • Value is evaluated at compile time.
  • Initiailized at declaration only.

'readonly':

  • Can be either instance-level or static.
  • Value is evaluated at run time.
  • Can be initialized in declaration or by code in the constructor.

C# 中“const”和“readonly”之间差异的简要概述:“const”:

  • 不能是静态的。
  • 编译时评估值
  • 仅在声明时初始化。

'只读':

  • 可以是实例级或静态。
  • 运行时评估值
  • 可以在声明或构造函数中的代码中初始化。

Correction:the above states const can't be static. That is a misnomer. They can't have the static keyword applied because they are already static.

更正:上述状态 const 不能是静态的。那是用词不当。它们不能应用 static 关键字,因为它们已经是静态的。

So you use const for static items that you want evaluated at compile-time.

因此,您将 const 用于要在编译时评估的静态项目。

回答by Greg Ogle

A good use of const is for keys of key/value pairs. For example, if you are still using AppSetting (instead of ApplicationSettings), it doesn't really make sense to loadthe name of the key to a configuration setting. If it is used in several place, stick the Key in a const.

const 的一个很好的用途是用于键/值对的键。例如,如果您仍在使用 AppSetting(而不是 ApplicationSettings),那么将密钥的名称加载到配置设置中实际上没有意义。如果它在多个地方使用,请将 Key 粘贴在 const 中。

回答by Greg Ogle

You should prefer modifier that are tested at compile time over modifier that are tested during runtime (in this context const over readonly). And you should always use the modifiers that support the semantic you need. If something isn't meant to be modified - protect it or someone will write something to it (by accident or by ignorance).

您应该更喜欢在编译时测试的修饰符而不是在运行时测试的修饰符(在这种情况下,const 而不是 readonly)。并且您应该始终使用支持您需要的语义的修饰符。如果某些东西不打算修改 - 保护它,否则有人会写一些东西(偶然或无知)。

回答by Daniel Auger

I typically only use const for things that I know will never everchange such as the speed of light in a vacuum.

我通常只将 const 用于我知道永远不会改变的事物,例如真空中的光速。

I prefer readonly for things that could potentiallychange. This way I only need to recompile one dll if a change happens. An exception to this rule of thumb is if the variable is private/protected/friendly to its own assembly. In those cases it is safe to use const.

我更喜欢 readonly 可能改变的事情。这样,如果发生更改,我只需要重新编译一个 dll。此经验法则的一个例外是变量是否对其自己的程序集是私有的/受保护的/友好的。在这些情况下,使用 const 是安全的。

回答by Ala Eddine JEBALI

Use constwhen your fields are of simple type(number, Boolean or string) and their values will never be changed. If you change their values, the project should be recompiled.

使用const时,你的字段是简单类型(数字,布尔值或字符串),它们的值永远不会改变。如果更改它们的值,则应重新编译项目。

Use readonlyfields when they are initialized from another source(file, database or other codes, ..etc.) but then they will not be changed.

readonly字段从另一个源(文件、数据库或其他代码等)初始化时使用字段,但它们不会被更改。

Use static readonlyfields when you want to make them shared by all instances.

static readonly您想让所有实例共享字段时,使用字段。