Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
337 views
in Technique[技术] by (71.8m points)

c# - 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).

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The problem you are facing has nothing to do with using a struct as the array type. Your syntax would also be invalid if you would use a 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.

As collection initializers and object initializers are just syntactic sugar, this is equivalent to

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...