声明一个常量数组常量、数组、声明

由网友(一秒メ速杀)分享简介:可能重复: 声明一个const的双重[]在C#中? 是否有可能写类似的东西来?公共常量字符串[]标题= {德国,西班牙,设置更正,过错};解决方案 是的,但你需要声明它只读而不是常量:公共只读的String []标题= {德国,西班牙,设置更正,过错};原因是,常量只能用于其值在编译时的字段。你给出的数组初始化不是一...

可能重复:   声明一个const的双重[]在C#中?

是否有可能写类似的东西来?

 公共常量字符串[]标题= {德国,西班牙,设置更正,过错};
 

解决方案

是的,但你需要声明它只读而不是常量

 公共只读的String []标题= {德国,西班牙,设置更正,过错};
 

原因是,常量只能用于其值在编译时的字段。你给出的数组初始化不是一个常数前pression在C#中,所以它会产生一个编译错误。

声明它只读解决了这个问题,因为该值没有被初始化,直到运行时(尽管它保证了第一次的阵列使用之前已经初始化)。

根据它是什么,你最终要实现的,你也可以考虑宣布一个枚举:

 公开枚举标题{德语,西班牙语,设置更正,过错};
 
在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 };

阅读全文

相关推荐

最新文章