声明一个常量数组 [英] Declare a Const Array
问题描述
可能重复:
声明一个const的双重[]在C#中?
是否有可能写类似的东西来?
公共常量字符串[]标题= {德国,西班牙,设置更正,过错};
是的,但你需要声明它只读
而不是常量
:
公共只读的String []标题= {德国,西班牙,设置更正,过错};
原因是,常量
只能用于其值在编译时的字段。你给出的数组初始化不是一个常数前pression在C#中,所以它会产生一个编译错误。
声明它只读
解决了这个问题,因为该值没有被初始化,直到运行时(尽管它保证了第一次的阵列使用之前已经初始化)。
根据它是什么,你最终要实现的,你也可以考虑宣布一个枚举:
公开枚举标题{德语,西班牙语,设置更正,过错};
Possible Duplicate:
Declaring a const double[] in C# ?
Is it possible to write something similar to?
public const string[] Titles = { "German", "Spanish", "Corrects", "Wrongs" };
Yes, but you need to declare it readonly
instead of const
:
public readonly string[] Titles = { "German", "Spanish", "Corrects", "Wrongs" };
The reason is that const
can only be applied to a field whose value is known at compile-time. The array initializer you've shown is not a constant expression in C#, so it produces a compiler error.
Declaring it readonly
solves that problem because the value is not initialized until run-time (although it's guaranteed to have initialized before the first time that the array is used).
Depending on what it is that you ultimately want to achieve, you might also consider declaring an enum:
public enum Titles { German, Spanish, Corrects, Wrongs };
这篇关于声明一个常量数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!