编译我的类时,我遇到了一个错误:
常量
'NamespaceName.ClassName.CONST_NAME'
无法标记为静态。
位于以下行:
public static const string CONST_NAME = "blah";
我在Java中一直都可以这样做。我做错了什么?为什么它不让我这样做?
编译我的类时,我遇到了一个错误:
常量
'NamespaceName.ClassName.CONST_NAME'
无法标记为静态。
位于以下行:
public static const string CONST_NAME = "blah";
我在Java中一直都可以这样做。我做错了什么?为什么它不让我这样做?
const
对象始终是static
的。
来自C#语言规范(PDF第287页,或PDF的第300页):
尽管常量被视为静态成员,但常量声明既不要求也不允许使用static修饰符。
编译器认为const成员是静态的,同时意味着常量值语义,这意味着常量的引用可能会被编译进使用代码中,作为常量成员的值,而不是成员的引用。
换句话说,一个包含值为10的const成员,可能被编译为在代码中使用数字10,而不是const成员的引用。
这与一个始终被编译为对字段的引用的static readonly字段不同。
请注意,这是预JIT。当JIT编译器发挥作用时,它可以将这两个都编译为目标代码的值。
C#中的const
与Java中的final
完全相同,唯一的区别是它始终是static
。在我看来,一个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;
}
}
嗯,现在我意识到这个问题是4年前提出的,但是由于我花了大约2个小时的时间,尝试各种不同的回答方式和代码格式化,所以我仍然发布它。
但是,为了记录,在此我仍然感觉有点傻。
final
与C#中的readonly
非常相似,而与const
完全不同。 - Ben Voigt来自MSDN:http://msdn.microsoft.com/en-us/library/acdd6hb7.aspx
...另外,虽然const字段是编译时常量,但readonly字段可用于运行时常量...
因此,在const字段中使用static就像试图在C/C++中定义静态一样...由于它在编译时被替换为其值,因此对于所有实例它只被初始化一次(= static)。
const与static相似,我们可以使用类名访问两个变量,但不同的是,静态变量可以修改,而常量不能。