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

为什么我的课堂上不能有“publicstaticconststring S=”stuff“?

  •  271
  • 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

    静态成员,一个常量 声明既不需要也不需要 允许使用静态修改器。

        3
  •  37
  •   Lasse V. Karlsen    16 年前

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

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

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

        4
  •  8
  •   jjnguy Julien Chastang    12 年前

    C#s const 与Java的完全相同 final static . 在我看来,这并不是一个真正必要的 变量为非- 可变非- 静止的

    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 年前

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

    ... 还有,虽然 常量字段是编译时常量

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

        6
  •  2
  •   soujanya    11 年前

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

    推荐文章