为什么我不能有“公共静态stringS =”东西“;在我的类?

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

常量'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 。 在我看来, constvariables不是非static ,但是如果你需要非static地访问constvariables,你可以这样做:

 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 (ie 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个小时的工作,包括尝试各种不同的回答方式和代码格式,所以我仍然发布这个问题。 🙂

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

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

…而且,虽然const字段是一个编译时常量 ,只读字段可用于运行时常量…

因此,在const字段中使用静态就像试图在C / C ++中定义(使用#define)静态…因为在编译期它被replace为它的值,所以对于所有实例(= static) 。

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