如何尽可能清楚地初始化结构的 const/static 数组?
class SomeClass
{
struct MyStruct
{
public string label;
public int id;
};
const MyStruct[] MyArray = {
{"a", 1}
{"b", 5}
{"q", 29}
};
};
最佳答案
首先,您真的必须要有一个可变结构吗?他们几乎总是一个坏主意。同样是公共(public)领域。在某些非常偶然的情况下,它们是合理的(通常两个部分在一起,如 ValueTuple
),但根据我的经验,它们非常罕见。
除此之外,我只是创建一个构造函数来获取两位数据:
class SomeClass
{
struct MyStruct
{
private readonly string label;
private readonly int id;
public MyStruct (string label, int id)
{
this.label = label;
this.id = id;
}
public string Label { get { return label; } }
public string Id { get { return id; } }
}
static readonly IList<MyStruct> MyArray = new ReadOnlyCollection<MyStruct>
(new[] {
new MyStruct ("a", 1),
new MyStruct ("b", 5),
new MyStruct ("q", 29)
});
}
注意 ReadOnlyCollection 的使用而不是暴露数组本身——这将使它不可变,避免 the problem exposing arrays directly . (代码显示确实初始化了一个结构数组 - 然后它只是将引用传递给 ReadOnlyCollection<>
的构造函数。)
关于c# - 在 C# 中初始化结构数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/309496/