2014-05-09 175 views
0

我一直在試圖通過數組初始化結構的多維數組...如何初始化結構

下面的代碼:

struct test_struct 
{ 
    double a, b, c, d, e; 

    public test_struct(double a, double b, double c, double d, double e) 
    { 
     this.a = a; 
     this.b = b; 
     this.c = c; 
     this.d = d; 
     this.e = e; 
    } 
}; 

test_struct[,,] Number = new test_struct[2, 3] 
{ 
    { 
     { 12.44, 525.38, -6.28, 2448.32, 632.04 }, 
     {-378.05, 48.14, 634.18, 762.48, 83.02 }, 
     { 64.92, -7.44, 86.74, -534.60, 386.73 }, 
    }, 
    { 
     { 48.02, 120.44, 38.62, 526.82, 1704.62 }, 
     { 56.85, 105.48, 363.31, 172.62, 128.48 }, 
     { 906.68, 47.12, -166.07, 4444.26, 408.62 }, 
    }, 
}; 

我不能使用循環或索引,以這樣做..我得到的錯誤是

數組初始值設定項只能用於變量或字段初始值設定項。嘗試使用新的表達式。

該代碼如何糾正?

+3

這是沒有有效的編譯的C#代碼。 –

+6

你確定逗號的數量? 'test_struct [,,] Number = new test_struct [2,3]'應該是'test_struct [,] Number = new test_struct [2,3]'的二維數組。 – dasblinkenlight

+1

錯誤信息中有什麼不清楚? –

回答

0

此代碼是有效的C#和應該做你想要什麼:

struct test_struct 
    { 
     double a, b, c, d, e; 
     public test_struct(double a, double b, double c, double d, double e) 
     { 
      this.a = a; 
      this.b = b; 
      this.c = c; 
      this.d = d; 
      this.e = e; 
     } 
    }; 

    private test_struct[,] Number = 
    { 
     { 

      new test_struct(12.44, 525.38, -6.28, 2448.32, 632.04), 
      new test_struct(-378.05, 48.14, 634.18, 762.48, 83.02), 
      new test_struct(64.92, -7.44, 86.74, -534.60, 386.73), 

     }, 

     { 
      new test_struct(48.02, 120.44, 38.62, 526.82, 1704.62), 
      new test_struct(56.85, 105.48, 363.31, 172.62, 128.48), 
      new test_struct(906.68, 47.12, -166.07, 4444.26, 408.62), 
     }, 
    }; 
+0

@PatrickHofman對不起,你是對的,相應地改變了答案。 –

0

最終的解決方案應該是,採取一切評論:

private test_struct[,] Number; 

public void test() 
{ 
    Number = new test_struct[2, 3] 
    { 
     { 
      new test_struct( 12.44, 525.38, -6.28, 2448.32, 632.04), 
      new test_struct(-378.05, 48.14, 634.18, 762.48, 83.02), 
      new test_struct( 64.92, -7.44, 86.74, -534.60, 386.73), 
     }, 
     { 
      new test_struct( 48.02, 120.44, 38.62, 526.82, 1704.62), 
      new test_struct( 56.85, 105.48, 363.31, 172.62, 128.48), 
      new test_struct(906.68, 47.12, -166.07, 4444.26, 408.62), 
     }, 
    }; 
} 
+0

感謝您的快速回復.. – user3620320