2014-05-09 142 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