jjn*_*guy 297 c# const constants
在尝试编译我的类时,我收到一个错误:
常量
'NamespaceName.ClassName.CONST_NAME'不能标记为静态.
在线:
public static const string CONST_NAME = "blah";
Run Code Online (Sandbox Code Playgroud)
我可以用Java一直这样做.我究竟做错了什么?为什么不让我这样做?
Joe*_*orn 542
const总是一个对象static.
ang*_*son 32
const成员被编译器视为静态,并暗示常量值语义,这意味着对常量的引用可能会被编译为使用代码作为常量成员的值,而不是对成员的引用.
换句话说,包含值10的const成员可能会被编译为使用它作为数字10的代码,而不是对const成员的引用.
这与静态只读字段不同,静态只读字段将始终编译为对字段的引用.
注意,这是预JIT.当JIT'ter发挥作用时,它可以将这两者编译为目标代码作为值.
小智 6
C#const与Java完全相同final,只不过它总是如此static.在我看来,const变量不是非必需的static,但如果你需要const非变量访问变量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;
}
}
Run Code Online (Sandbox Code Playgroud)
嗯,现在我意识到这个问题是在4年前被问到的,但是由于我花了大约2个小时的工作,包括尝试各种不同的回答方式和代码格式,在这个答案中,我仍然发布它.:)
但是,为了记录,我仍然觉得有点傻.
来自MSDN:http://msdn.microsoft.com/en-us/library/acdd6hb7.aspx
...此外,虽然const字段是编译时常量,但readonly字段可用于运行时常量...
因此在const字段中使用static就像尝试在C/C++中创建一个已定义的(带#define)静态...因为它在编译时被替换为它的值,当然它为所有实例启动一次(= static) .