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

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

行线处:

public static const string CONST_NAME = "blah";

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


const对象总是静态的。


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

即使考虑了常数 静态成员,常量 声明既不要求也不要求 允许使用静态修饰符。


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

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

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

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


c#的const和Java的final是完全一样的东西,除了它绝对总是静态的。在我看来,const变量不是必须是非静态的,但是如果你需要非静态地访问一个const变量,你可以这样做:

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不能。


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

... 此外,虽然const字段是编译时常量,但readonly字段可用于运行时常量……

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