如何初始化结构体数组? [英] How to initialize array of struct?
问题描述
功能失调的示例:
public struct MyStruct { public int i, j; }
static readonly MyStruct [] myTable = new MyStruct [3]
{
{0, 0}, {1, 1}, {2, 2}
}
我知道此代码无效。现在,我该如何记下来(正确的语法)?
I know that this code doesn't work. Now how do I write this down please (proper syntax)?
其背后的想法如下。 Afaik struct数组的元素是值类型,因此myTable指向包含三个MyStruct对象的内存位置(而不是包含三个指向MyStruct对象的(未初始化)指针的内存位置)。
The thought behind this is the following. Afaik the elements of arrays of struct are value types, so myTable points to a memory location containing three MyStruct objects (and not to a memory location containing three (uninitialized) pointers to MyStruct objects).
那么我该如何初始化那些MyStruct对象,正确的语法是什么?我不必再分配它们了,对吧?
So how do I go about initializing those MyStruct objects, what would be the right syntax? I don't have to allocate them anymore, right?
推荐答案
您需要使用 MyStruct
,您可以使用 new
关键字创建。
You need to use actual instances of your MyStruct
, which you can create with the new
keyword.
这应该有效...
struct MyStruct
{
int i, j;
public MyStruct(int a, int b)
{
i = a;
j = b;
}
}
static MyStruct[] myTable = new MyStruct[3]
{
new MyStruct(0, 0),
new MyStruct(1, 1),
new MyStruct(2, 2)
};
这篇关于如何初始化结构体数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!