为什么我不能拥有“ public static const string S =” stuff&quot ;;在我的班级?

StackOverflow https://stackoverflow.com/questions/408192

  •  03-07-2019
  •  | 
  •  

当我尝试编译我的课时,我收到一个错误:

  

常量'NamespaceName.ClassName.CONST_NAME'无法标记为静态。

在这一行:

public static const string CONST_NAME = "blah";

我可以用Java一直这样做。我究竟做错了什么?为什么不让我这样做?

有帮助吗?

解决方案

const 对象始终是 static

其他提示

来自 C#语言规范 (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个小时的工作,包括尝试各种不同的回答方式和代码格式化,这个答案,我仍然发布它。 :)

但是,为了记录,我仍然觉得有点傻。

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

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

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

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top