是否可以写出类似于下面的内容?
public const string[] Titles = { "German", "Spanish", "Corrects", "Wrongs" };
是否可以写出类似于下面的内容?
public const string[] Titles = { "German", "Spanish", "Corrects", "Wrongs" };
当前回答
可以将数组声明为只读数组,但请记住,可以更改只读数组的元素。
public readonly string[] Titles = { "German", "Spanish", "Corrects", "Wrongs" };
...
Titles[0] = "bla";
可以考虑像Cody建议的那样使用enum或IList。
public readonly IList<string> ITitles = new List<string> {"German", "Spanish", "Corrects", "Wrongs" }.AsReadOnly();
其他回答
快速的解决方法,说不定对别人有帮助。我需要一个字符串[]作为Attribute的参数(在某些理论中为测试用例传递内联数据)。Readonly在这里没用。但是,我最后做的是:
const string foo = "a|b|c";
[InlineData(foo)]
public void Test(string fooString)
{
var foo = fooString.Split("|"); // foo == {"a","b","c"}
...
}
为了完整起见,现在我们也有immutablearray供我们使用。这应该是真正不可变的:
public readonly static ImmutableArray<string> Titles =
ImmutableArray.Create(new[] { "German", "Spanish", "Corrects", "Wrongs" });
需要System.Collections.Immutable NuGet引用。
我相信你只能让它只读。
最好的选择:
public static readonly byte[] ZeroHash = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
数组可能是一种只能在这里求值的东西 运行时。常量必须在编译时求值。尝试使用"readonly" 而不是"const"。