【问题标题】:Const array of strings [duplicate]常量字符串数组[重复]
【发布时间】:2012-12-13 08:19:03
【问题描述】:

可能重复:
Declare a Const Array

我需要类中的 const 字符串数组。类似的东西

public class some_class_t
{
    public const string[] names = new string[4]
    {
        "alpha", "beta", "gamma", "delta"
    };
}

但是这段代码会导致错误:

引用类型“string[]”的常量“names”只能用 null 初始化。

我该怎么办?

【问题讨论】:

  • 数组是可变的。除非它们为空,否则它们不能保持不变。

标签: c# .net arrays string constants


【解决方案1】:

将其声明为readonly 而不是const

public readonly string[] names = { "alpha", "beta", "gamma", "delta" };

【讨论】:

  • 并声明它static 所以我会使用public readonly string[] names = { "alpha", "beta", "gamma", "delta" };
  • mike nelson 的意思是“public static readonly string[] names = { "alpha", "beta", "gamma", "delta" };
  • 为什么会被接受?而问题是关于const 而不是readonly...
  • 因为它符合 OP 的意图(据说)。您必须有能力认识到这一点,尤其是作为开发人员。
猜你喜欢
  • 2010-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-01
相关资源
最近更新 更多