C# 静态和常量有什么区别?
正如它所说。我即将在我正在编写的程序中定义一个常量或静态值,但我很困惑为什么要使用其中之一。作为唯一相关的问题,我在问这个问题时遇到的人想要将某些东西标记为我怀疑我不是唯一一个对这些概念有点迷失的人。
那么为什么我要使用静态以及为什么要使用常量呢?有什么区别?它们是同义词吗?如果是这样,那很酷,但如果不是,为什么不呢?谢谢!
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
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 asreadonly
(or given a getter but no setter). If it is marked asreadonly
then it is essentially a constant, but it is handled at runtime, not by the compiler.首先,它们不是同义词。
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, readStatic Classes and Static Members
.五分钟后我发现 这个。
还有其他评论吗?
And wouldn't you know it five minutes later I find this.
Any other comments?