是否可以写出类似于下面的内容?
public const string[] Titles = { "German", "Spanish", "Corrects", "Wrongs" };
是否可以写出类似于下面的内容?
public const string[] Titles = { "German", "Spanish", "Corrects", "Wrongs" };
当前回答
这是一种做你想做的事情的方法:
using System;
using System.Collections.ObjectModel;
using System.Collections.Generic;
public ReadOnlyCollection<string> Titles { get { return new List<string> { "German", "Spanish", "Corrects", "Wrongs" }.AsReadOnly();}}
它非常类似于做一个只读数组。
其他回答
是的,但是你需要声明它为readonly而不是const:
public static readonly string[] Titles = { "German", "Spanish", "Corrects", "Wrongs" };
原因是const只能应用于编译时已知值的字段。您所展示的数组初始化器不是c#中的常量表达式,因此会产生编译器错误。
声明它为readonly可以解决这个问题,因为值直到运行时才初始化(尽管可以保证在第一次使用数组之前已经初始化)。
根据你最终想要实现的目标,你也可以考虑声明一个枚举:
public enum Titles { German, Spanish, Corrects, Wrongs };
为了完整起见,现在我们也有immutablearray供我们使用。这应该是真正不可变的:
public readonly static ImmutableArray<string> Titles =
ImmutableArray.Create(new[] { "German", "Spanish", "Corrects", "Wrongs" });
需要System.Collections.Immutable NuGet引用。
这是一种做你想做的事情的方法:
using System;
using System.Collections.ObjectModel;
using System.Collections.Generic;
public ReadOnlyCollection<string> Titles { get { return new List<string> { "German", "Spanish", "Corrects", "Wrongs" }.AsReadOnly();}}
它非常类似于做一个只读数组。
你可以采用一种不同的方法:定义一个常量字符串来表示你的数组,然后在你需要它的时候把字符串分割成一个数组。
const string DefaultDistances = "5,10,15,20,25,30,40,50";
public static readonly string[] distances = DefaultDistances.Split(',');
这种方法为您提供了一个可以存储在配置中并在需要时转换为数组的常量。
最好的选择:
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 };