[英]C# What is the difference between static and constant?
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! 谢谢!
const
is dealt with at compile time. const
在编译时处理。 Every reference to that constant is replaced by the constant value. 每个对该常量的引用都被常量值替换。
static
is very different. static
是非常不同的。 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). 它可以编辑,除非标记为readonly
(或给定一个getter但没有setter)。 If it is marked as readonly
then it is essentially a constant, but it is handled at runtime, not by the compiler. 如果它被标记为readonly
那么它本质上是一个常量,但它在运行时处理,而不是由编译器处理。
First off, they are not synonymous. 首先,它们不是同义词。
static
marks a member as belonging to the type . static
将成员标记为属于该类型 。 const
means the member value cannot be changed. const
表示不能更改成员值 。 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
. 为了更好地理解static
使用方式,请阅读Static Classes and Static Members
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.