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

When, if ever, should we use const?(什么时候,如果有的话,我们应该使用 const 吗?)
本文介绍了什么时候,如果有的话,我们应该使用 const 吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Const 被烘焙到客户端代码中.Readonly 不是.但是 const 更快.不过可能只有一点点.

Const is baked into the client code. Readonly isn't. But const is faster. May be only slightly though.

问题是,在任何情况下您应该更喜欢 const 而不是 readonly?或者换种说法,我们实际上总是最好使用 readonly 而不是 const (记住上面所说的烘焙事情)?

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

推荐答案

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

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.

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

哦!除非你已经测量过,否则永远不要假设 const 比只读字段快.有 JIT 优化可以做到这一点,所以它实际上是完全一样的.

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 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)