How to initialize array of struct?

前端 未结 2 1062
南旧
南旧 2020-12-06 13:25

Dysfunctional Example:

public struct MyStruct { public int i, j; }

static readonly MyStruct [] myTable = new MyStruct [3] 
{
    {0, 0}, {1, 1}, {2, 2}
}


        
相关标签:
2条回答
  • 2020-12-06 13:53

    You need to use actual instances of your MyStruct, which you can create with the new keyword.

    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)
    };
    
    0 讨论(0)
  • 2020-12-06 13:53

    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.

    0 讨论(0)
提交回复
热议问题