声明一个常量数组 [英] Declare a const array
问题描述
是否可以写出类似下面的内容?
Is it possible to write something similar to the following?
public const string[] Titles = { "German", "Spanish", "Corrects", "Wrongs" };
推荐答案
可以,但是需要声明为 readonly
而不是 const
:
Yes, but you need to declare it readonly
instead of const
:
public static readonly string[] Titles = { "German", "Spanish", "Corrects", "Wrongs" };
原因是 const
只能应用于其值在编译时已知的字段.您展示的数组初始值设定项不是 C# 中的常量表达式,因此会产生编译器错误.
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.
声明它 readonly
解决了这个问题,因为值直到运行时才被初始化(尽管它保证在第一次使用数组之前已经初始化).
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屋!