简体   繁体   English

如何初始化结构数组?

[英]How to initialize array of struct?

Dysfunctional Example:功能失调的例子:

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)?现在我该如何写下来(正确的语法)?

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). Afaik struct arrays 的元素是值类型,因此 myTable 指向包含三个 MyStruct 对象的 memory 位置(而不是指向包含三个 MyStruct 对象的 memory 位置的指针)

So how do I go about initializing those MyStruct objects, what would be the right syntax?那么我如何 go 关于初始化那些 MyStruct 对象,正确的语法是什么? I don't have to allocate them anymore, right?我不必再分配它们了,对吧?

The problem you are facing has nothing to do with using a struct as the array type.您面临的问题与使用 struct 作为数组类型无关。 Your syntax would also be invalid if you would use a class.如果您使用 class,您的语法也会无效。

This works:这有效:

MyStruct [] myTable = new MyStruct [] 
{
    new MyStruct { i = 0, j = 0 },
    new MyStruct { i = 1, j = 1 },
    new MyStruct { i = 2, j = 2 }
};

You have to use collection initializers together with object initializers.您必须将集合初始化程序与 object 初始化程序一起使用。

As collection initializers and object initializers are just syntactic sugar, this is equivalent to由于集合初始化器和 object 初始化器只是语法糖,这相当于

MyStruct [] myTable = new MyStruct[3]; 
var tmp = new MyStruct();
tmp.i = 0;
tmp.j = 0;
myTable[0] = tmp;
// and so on...

What you really want with an array of structs is this:你真正想要的结构数组是这样的:

MyStruct [] myTable = new MyStruct[3]; 
myTable[0].i = 0;
myTable[0].j = 0;
// and so on...

But this can't be achieved using the short hand initializer syntax.但这不能使用简写初始化语法来实现。

You need to use actual instances of your MyStruct , which you can create with the new keyword.您需要使用MyStruct的实际实例,您可以使用new关键字创建它。

This should work...这应该工作...

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)
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM