是否可以写出类似于下面的内容?

public const string[] Titles = { "German", "Spanish", "Corrects", "Wrongs" };

当前回答

作为一种替代方法,要解决使用只读数组可以修改元素的问题,可以使用静态属性。(单个元素仍然可以更改,但这些更改只会在数组的本地副本上进行。)

public static string[] Titles 
{
    get
    {
        return new string[] { "German", "Spanish", "Corrects", "Wrongs"};
    }
}

当然,这不是特别有效,因为每次都会创建一个新的字符串数组。

其他回答

我相信你只能让它只读。

是的,但是你需要声明它为readonly而不是const:

public static readonly string[] Titles = { "German", "Spanish", "Corrects", "Wrongs" };

原因是const只能应用于编译时已知值的字段。您所展示的数组初始化器不是c#中的常量表达式,因此会产生编译器错误。

声明它为readonly可以解决这个问题,因为值直到运行时才初始化(尽管可以保证在第一次使用数组之前已经初始化)。

根据你最终想要实现的目标,你也可以考虑声明一个枚举:

public enum Titles { German, Spanish, Corrects, Wrongs };

如果你在IReadOnlyList接口后面声明了一个数组,你会得到一个常量数组,在运行时声明常量值:

public readonly IReadOnlyList<string> Titles = new [] {"German", "Spanish", "Corrects", "Wrongs" };

在. net 4.5及更高版本中可用。

这是一种做你想做的事情的方法:

using System;
using System.Collections.ObjectModel;
using System.Collections.Generic;

public ReadOnlyCollection<string> Titles { get { return new List<string> { "German", "Spanish", "Corrects", "Wrongs" }.AsReadOnly();}}

它非常类似于做一个只读数组。

.NET Framework v4.5+解决方案,改进了tdbeckett的答案:

using System.Collections.ObjectModel;

// ...

public ReadOnlyCollection<string> Titles { get; } = new ReadOnlyCollection<string>(
  new string[] { "German", "Spanish", "Corrects", "Wrongs" }
);

注意:假定集合在概念上是常量,在类级别声明它时将其设置为静态可能是有意义的。

上面的:

Initializes the property's implicit backing field once with the array. Note that { get; } - i.e., declaring only a property getter - is what makes the property itself implicitly read-only (trying to combine readonly with { get; } is actually a syntax error). Alternatively, you could just omit the { get; } and add readonly to create a field instead of a property, as in the question, but exposing public data members as properties rather than fields is a good habit to form. Creates an array-like structure (allowing indexed access) that is truly and robustly read-only (conceptually constant, once created), both with respect to: preventing modification of the collection as a whole (such as by removing or adding elements, or by assigning a new collection to the variable). preventing modification of individual elements. (Even indirect modification isn't possible - unlike with an IReadOnlyList<T> solution, where a (string[]) cast can be used to gain write access to the elements, as shown in mjepsen's helpful answer. The same vulnerability applies to the IReadOnlyCollection<T> interface, which, despite the similarity in name to class ReadOnlyCollection, does not even support indexed access, making it fundamentally unsuitable for providing array-like access.)