问题描述
在过去的一个周末,我跑了放入查找中的用法。 p>
问题代码如下:
内部静态类SomeStaticClass
{
private const int CommonlyUsedValue = 42;
内部静态字符串UseCommonlyUsedValue(...)
{
//一些代码
value = CommonlyUsedValue + ...;
返回值.ToString();
}
}
我措手不及,因为这似乎是静态函数正在使用非静态字段,某些静态函数在静态类中对其进行了很好的编译!
规范指出(第10.4节):
现在,它变得更有意义了,因为常量被认为是静态成员,但是句子的其余部分令我有些惊讶。为什么常量声明既不需要也不允许静态修饰符?诚然,我并不十分了解规范,以至于一开始就无法理解,但是为什么要做出这样的决定:如果常量被认为是静态的,则不强迫常量使用static修饰符?
看着该段的最后一句话,我无法弄清楚它是否直接与前一条语句有关,并且常量开头是否有隐式的静态修饰符,或者是否作为常量的另一条规则独立存在。有人可以帮我解决这个问题吗?
基本上, const 意味着静态由于该值无法在运行时更改,因此请参见> strong>。您没有理由声明 static const ,因为它已经隐含了,语言设计者决定使语言语法反映出来。
规范语言基本上说:常量始终是静态的,因此您不能明确地说静态和常量,因为它们是多余的。
I was plugging away on an open source project this past weekend when I ran into a bit of code that confused me to look up the usage in the C# specification.
The code in questions is as follows:
internal static class SomeStaticClass
{
private const int CommonlyUsedValue = 42;
internal static string UseCommonlyUsedValue(...)
{
// some code
value = CommonlyUsedValue + ...;
return value.ToString();
}
}
I was caught off guard because this appears to be a non static field being used by a static function which some how compiled just fine in a static class!
The specification states (§10.4):
So now it makes a little more sense because constants are considered static members, but the rest of the sentence is a bit surprising to me. Why is it that a constant-declaration neither requires nor allows a static modifier? Admittedly I did not know the spec well enough for this to immediately make sense in the first place, but why was the decision made to not force constants to use the static modifier if they are considered static?
Looking at the last sentence in that paragraph, I cannot figure out if it is regarding the previous statement directly and there is some implicit static modifier on constants to begin with, or if it stands on its own as another rule for constants. Can anyone help me clear this up?
Basically, const implies static already, since the value cannot be changed at runtime. There's no reason for you to ever declare static const, since it's already implied, and the language designers decided to make the language syntax reflect that.
The specification language is basically saying "Const is always static, so you can't explicitly say static and const since it's redundant."
这篇关于在静态类中使用const的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!