本文翻译自:Why can't I have “public static const string S = ”stuff"; in my Class?
When trying to compile my class I get an error: 在尝试编译我的类时,我收到一个错误:
The constant
'NamespaceName.ClassName.CONST_NAME'
cannot be marked static. 常量'NamespaceName.ClassName.CONST_NAME'
不能标记为静态。
at the line: 在线:
public static const string CONST_NAME = "blah";
I could do this all of the time in Java. 我可以用Java一直这样做。 What am I doing wrong? 我究竟做错了什么? And why doesn't it let me do this? 为什么不让我这样做?
#1楼
参考:https://stackoom.com/question/1IbK/为什么我不能拥有-public-static-const-string-S-stuff-在我的班级
#2楼
C#'s const
is the exact same thing as Java's final
, except it's absolutely always static
. C#的const
与Java的final
是完全相同的,除了它绝对是static
。 In my opinion, it's not really necessary for a const
variable to be non- static
, but if you need to access a const
variable non- static
-ly, you can do: 在我看来, const
变量不是非static
,但如果你需要非static
地访问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;
}
}
Well, now I realize this question was asked 4 years ago, but since I put around 2 hours of work, consisting of trying all sorts of different ways of answering and code formatting, into this answer, I'm still posting it. 嗯,现在我意识到这个问题是在4年前被问到的,但是由于我花了大约2个小时的工作,包括尝试各种不同的回答方式和代码格式化,在这个答案中,我仍然发布它。 :) :)
But, for the record, I still feel kinda silly. 但是,为了记录,我仍然觉得有点傻。
#3楼
const类似于static我们可以访问带有类名的两个变量,但是diff是可以修改的静态变量而const不能。
#4楼
From MSDN: http://msdn.microsoft.com/en-us/library/acdd6hb7.aspx 来自MSDN: http : //msdn.microsoft.com/en-us/library/acdd6hb7.aspx
... Also, while a const field is a compile-time constant , the readonly field can be used for runtime constants... ...此外,虽然const字段是编译时常量 ,但readonly字段可用于运行时常量...
So using static in const fields is like trying to make a defined (with #define) static in C/C++... Since it is replaced with its value in compile-time of course it is initiated once for all instances (=static). 因此在const字段中使用static就像尝试在C / C ++中创建一个已定义的(带#define)静态...因为它在编译时被替换为它的值,当然它会为所有实例启动一次(= static) 。
#5楼
const
对象始终是static
。
#6楼
From the C# language specification (PDF page 287 - or 300th page of the PDF): 从C#语言规范 (PDF第287页 - 或PDF的第300页):
Even though constants are considered static members, a constant declaration neither requires nor allows a static modifier. 尽管常量被认为是静态成员,但常量声明既不需要也不允许使用静态修饰符。