声明一个常量数组 [英] Declare a Const Array

查看:195
本文介绍了声明一个常量数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  

可能重复:
  声明一个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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆