为什么我不能';public static const string S = "stuff";;在我班上?

当试图编译我的类时,我得到一个错误:

常量'NamespaceName.ClassName.CONST_NAME'不能被标记为static。

行线处:

public static const string CONST_NAME = "blah";

我可以在Java中一直这样做。我做错了什么?为什么它不让我这么做呢?

162313 次浏览

const对象总是static

c#语言规范 (PDF页287 -或PDF页第300页):

即使考虑常量 静态成员,常量 声明既不要求也不要求 允许一个静态修饰符

编译器认为const成员是静态的,并隐含常量值语义,这意味着对常量的引用可以作为常量成员的值编译到using代码中,而不是对该成员的引用。

换句话说,包含值10的const成员可能会被编译成将其用作数字10的代码,而不是对const成员的引用。

这与静态只读字段不同,后者将始终作为字段的引用编译。

注意,这是预jit。当JIT'ter开始发挥作用时,它可能会将这两者作为值编译到目标代码中。

c#的const与Java的final完全相同,除了它绝对总是static。在我看来,const变量不一定是非-static,但如果你需要访问一个非-staticconst变量,你可以这样做:

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个小时的工作,包括尝试各种不同的回答方式和代码格式,到这个答案,我仍然在发布它。:)

不过,我还是觉得自己有点傻。

Const类似于static,我们可以通过类名访问这两个变量,但diff是静态变量,可以修改,而Const不能。

From MSDN: http://msdn.microsoft.com/en-us/library/acdd6hb7.aspx

... 此外,当const字段是一个编译时常量时,只读字段可用于运行时常量…

因此,在const字段中使用static就像试图在C/ c++中创建一个已定义的静态(使用#define)…因为它在编译时被替换为它的值,所以对于所有实例(=static),它都会被初始化一次。