代码之家  ›  专栏  ›  技术社区  ›  jjnguy Julien Chastang

为什么我的类中不能有“public static const string S=”stuff“?

  •  428
  • jjnguy Julien Chastang  · 技术社区  · 16 年前

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

    常数 'NamespaceName.ClassName.CONST_NAME' 不能标记为静态。

    在线路上:

    public static const string CONST_NAME = "blah";
    

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

    6 回复  |  直到 7 年前
        1
  •  676
  •   Cole Tobin Matt    10 年前

    A. const 对象总是 static .

        2
  •  113
  •   splattne    16 年前

    C# language specification (PDF第287页或PDF的第300页):

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

        3
  •  37
  •   Lasse V. Karlsen    16 年前

    const成员被编译器认为是静态的,也意味着常量值语义,这意味着对常量的引用可能会被编译成使用代码作为常量成员的值,而不是对成员的引用。

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

    这与静态只读字段不同,静态只读字段将始终被编译为对该字段的引用。

    注意,这是JIT之前的版本。当JIT'ter发挥作用时,它可能会将这两个值编译为目标代码中的值。

        4
  •  8
  •   jjnguy Julien Chastang    12 年前

    C# const 与Java完全相同 final ,但绝对总是这样 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个小时的时间,包括尝试各种不同的答案和代码格式,我仍然在发布这个答案。:)

    但是,郑重声明,我仍然觉得有点傻。

        5
  •  7
  •   uriel    11 年前

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

    …此外,虽然 const字段是编译时常数 ,只读字段可用于运行时常量。..

    因此,在const字段中使用static就像在C/C++中试图使一个已定义的(带有#define)静态。..由于它在编译时被其值替换,因此它对所有实例都会启动一次(=静态)。

        6
  •  2
  •   soujanya    12 年前

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

    推荐文章