[英]Initializing an Array of Structs in C#
How can I initialize a const / static array of structs as clearly as possible? 如何尽可能清楚地初始化const / static数组结构?
class SomeClass
{
struct MyStruct
{
public string label;
public int id;
};
const MyStruct[] MyArray = {
{"a", 1}
{"b", 5}
{"q", 29}
};
};
Firstly, do you really have to have a mutable struct? 首先,你真的必须拥有一个可变的结构吗? They're almost always a bad idea.
他们几乎总是一个坏主意。 Likewise public fields.
同样公共领域。 There are some very occasional contexts in which they're reasonable (usually both parts together, as with
ValueTuple
) but they're pretty rare in my experience. 有一些非常偶然的背景,它们是合理的(通常两个部分在一起,就像
ValueTuple
),但在我的经验中它们是非常罕见的。
Other than that, I'd just create a constructor taking the two bits of data: 除此之外,我只是创建一个构造函数来获取两位数据:
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)
});
}
Note the use of ReadOnlyCollection instead of exposing the array itself - this will make it immutable, avoiding the problem exposing arrays directly . 注意使用ReadOnlyCollection而不是暴露数组本身 - 这将使它不可变,避免直接暴露数组的问题 。 (The code show does initialize an array of structs - it then just passes the reference to the constructor of
ReadOnlyCollection<>
.) (代码show会初始化一个结构数组 - 然后它只是将引用传递给
ReadOnlyCollection<>
的构造函数。)
Are you using C# 3.0? 你在使用C#3.0吗? You can use object initializers like so:
你可以像这样使用对象初始化器:
static MyStruct[] myArray =
new MyStruct[]{
new MyStruct() { id = 1, label = "1" },
new MyStruct() { id = 2, label = "2" },
new MyStruct() { id = 3, label = "3" }
};
You cannot initialize reference types by default other than null. 默认情况下,您不能初始化引用类型,而不是null。 You have to make them readonly.
你必须让他们只读。 So this could work;
所以这可行;
readonly MyStruct[] MyArray = new MyStruct[]{
new MyStruct{ label = "a", id = 1},
new MyStruct{ label = "b", id = 5},
new MyStruct{ label = "c", id = 1}
};
Change const
to static readonly
and initialise it like this 将
const
更改为static readonly
,并像这样初始化它
static readonly MyStruct[] MyArray = new[] {
new MyStruct { label = "a", id = 1 },
new MyStruct { label = "b", id = 5 },
new MyStruct { label = "q", id = 29 }
};
I'd use a static constructor on the class that sets the value of a static readonly array. 我在类上使用静态构造函数来设置静态只读数组的值。
public class SomeClass
{
public readonly MyStruct[] myArray;
public static SomeClass()
{
myArray = { {"foo", "bar"},
{"boo", "far"}};
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.