是否可以编写类似于以下内容的内容?
public const string[] Titles = { "German", "Spanish", "Corrects", "Wrongs" };
#1楼
对于我的需要,我定义了static
数组,而不是不可能的const
,它可以工作: public static string[] Titles = { "German", "Spanish", "Corrects", "Wrongs" };
#2楼
您可以采取另一种方法:定义一个常量字符串来表示您的数组,然后在需要时将其拆分为一个数组,例如
const string DefaultDistances = "5,10,15,20,25,30,40,50";
public static readonly string[] distances = DefaultDistances.Split(',');
这种方法为您提供了一个常量,可以将其存储在配置中,并在需要时转换为数组。
#3楼
这是一种执行所需操作的方法:
using System;
using System.Collections.ObjectModel;
using System.Collections.Generic;
public ReadOnlyCollection<string> Titles { get { return new List<string> { "German", "Spanish", "Corrects", "Wrongs" }.AsReadOnly();}}
这与执行只读数组非常相似。
#4楼
作为替代方案,要解决带有只读数组的元素可能被修改的问题,可以改用static属性。 (仍可以更改各个元素,但是这些更改将仅在数组的本地副本上进行。)
public static string[] Titles
{
get
{
return new string[] { "Ge