How to initialize array of struct?

前端 未结 2 1066
南旧
南旧 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)
    };
    

提交回复
热议问题