C# 静态和常量有什么区别?

发布于 2024-10-08 17:18:54 字数 257 浏览 2 评论 0原文

正如它所说。我即将在我正在编写的程序中定义一个常量或静态值,但我很困惑为什么要使用其中之一。作为唯一相关的问题,我在问这个问题时遇到的人想要将某些东西标记为我怀疑我不是唯一一个对这些概念有点迷失的人。

那么为什么我要使用静态以及为什么要使用常量呢?有什么区别?它们是同义词吗?如果是这样,那很酷,但如果不是,为什么不呢?谢谢!

As it says. I am about to define a constant, or static, value in a program I am writing and am confused as to why you would use one or the other. As the only related question i get when asking this question deals with someone who wants to mark something as both static and constant at once I suspect I am not the only person a bit lost with these concepts.

So why would I use static and why would I use constant? What's the distinction? Are they synonymous? If so, that's cool, but if not why not? Thanks!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

漆黑的白昼 2024-10-15 17:18:54

const 在编译时处理。对该常量的每个引用都被常量值替换。

static 是非常不同的。它是一个仅存在一次但属于该类型的所有对象的变量。除非标记为只读(或给定 getter 但没有 setter),否则可以对其进行编辑。如果它被标记为只读,那么它本质上是一个常量,但它是在运行时处理的,而不是由编译器处理的。

const is dealt with at compile time. Every reference to that constant is replaced by the constant value.

static is very different. It is a variable which exists only once but belongs to all objects of that type. It can be edited unless marked as readonly (or given a getter but no setter). If it is marked as readonly then it is essentially a constant, but it is handled at runtime, not by the compiler.

预谋 2024-10-15 17:18:54

首先,它们不是同义词。

  • static 将成员标记为属于输入
  • const 表示成员值无法更改。该值在编译时确定并在出现的任何地方进行替换。

为了更好地了解如何使用static,请阅读 静态类和静态成员

First off, they are not synonymous.

  • static marks a member as belonging to the type.
  • const means the member value cannot be changed. The value is determined at compile time and substituted wherever it appears.

For better understanding of how static is to be used, read Static Classes and Static Members.

怎樣才叫好 2024-10-15 17:18:54

五分钟后我发现 这个

还有其他评论吗?

And wouldn't you know it five minutes later I find this.

Any other comments?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文