【发布时间】:2010-09-29 07:43:07
【问题描述】:
尝试编译我的类时出现错误:
常量
'NamespaceName.ClassName.CONST_NAME'不能标记为静态。
在线:
public static const string CONST_NAME = "blah";
我可以一直在 Java 中做到这一点。我究竟做错了什么?为什么它不让我这样做?
【问题讨论】:
尝试编译我的类时出现错误:
常量
'NamespaceName.ClassName.CONST_NAME'不能标记为静态。
在线:
public static const string CONST_NAME = "blah";
我可以一直在 Java 中做到这一点。我究竟做错了什么?为什么它不让我这样做?
【问题讨论】:
const 对象始终为 static。
【讨论】:
来自C# language specification(PDF 第 287 页 - 或 PDF 第 300 页):
即使考虑了常量 静态成员,常量 声明既不要求也不 允许使用静态修饰符。
【讨论】:
编译器认为 const 成员是静态的,并且暗示了常量值语义,这意味着对常量的引用可能会编译到使用代码中作为常量成员的值,而不是对成员的引用。
换句话说,包含值 10 的 const 成员可能会被编译成将其用作数字 10 的代码,而不是对 const 成员的引用。
这与静态只读字段不同,后者将始终编译为对该字段的引用。
注意,这是预 JIT。当 JIT'ter 发挥作用时,它可能会将这两者作为值编译到目标代码中。
【讨论】:
C# 的const 与Java 的final 完全相同,但它绝对总是static。在我看来,const 变量不一定非static,但如果您需要访问非const 变量非static-ly,您可以这样做:
class MyClass
{
private const int myLowercase_Private_Const_Int = 0;
public const int MyUppercase_Public_Const_Int = 0;
/*
You can have the `private const int` lowercase
and the `public int` Uppercase:
*/
public int MyLowercase_Private_Const_Int
{
get
{
return MyClass.myLowercase_Private_Const_Int;
}
}
/*
Or you can have the `public const int` uppercase
and the `public int` slighly altered
(i.e. an underscore preceding the name):
*/
public int _MyUppercase_Public_Const_Int
{
get
{
return MyClass.MyUppercase_Public_Const_Int;
}
}
/*
Or you can have the `public const int` uppercase
and get the `public int` with a 'Get' method:
*/
public int Get_MyUppercase_Public_Const_Int()
{
return MyClass.MyUppercase_Public_Const_Int;
}
}
好吧,现在我意识到这个问题是 4 年前提出的,但是由于我投入了大约 2 个小时的工作,包括尝试各种不同的回答方式和代码格式,所以我仍然在发布它. :)
但是,为了记录,我还是觉得有点傻。
【讨论】:
final 的行为与 C# readonly 完全一样,完全不像 const。
来自 MSDN:http://msdn.microsoft.com/en-us/library/acdd6hb7.aspx
...此外,虽然 const 字段是编译时常量,但 readonly 字段可用于运行时常量...
因此,在 const 字段中使用静态就像试图在 C/C++ 中创建一个已定义的(使用#define)静态...因为它在编译时被替换为它的值,当然它会为所有实例启动一次( =静态)。
【讨论】:
const 类似于 static 我们可以使用类名访问这两个变量,但 diff 是静态变量可以修改而 const 不能。
【讨论】: