使用两级数组c#填充复杂结构

时间:2014-11-03 03:58:16

标签: c# nullreferenceexception

我想设置我的结构写入en C#的值,我得到一个错误。

    private struct pack2
   {
      public float var;
      public float [3]var2;
   }
    private struct pack
   {
      public pack2[] ster;
   }

private void recv()
{
     pack mystruct;
     mystruct.ster = new pack2[4]; // Because I need to declare 4 structures of pack2
     mystruct.ster[0].var = 2F;
     mystruct.ster[0].var[0] = 1F; // error
} 

错误:NullReferenceException未处理,Addinfo:对象引用未设置为对象的实例

我该如何解决?

解决:

private struct pack2
       {
          public float var;
          public float [3]var2;
       }
        private struct pack
       {
          public pack2[] ster;
       }

    private void recv()
    {
         pack mystruct;
         mystruct.ster = new pack2[4]; // Because I need to declare 4 structures of pack2
         mystruct.ster[0].var = 2F;
         mystruct.ster[0].var2 = new float[3]; // Because I need 3 floats on each pack2
         mystruct.ster[1].var2 = new float[3]; // Because I need 3 floats on each pack2
         mystruct.ster[2].var2 = new float[3]; // Because I need 3 floats on each pack2
         mystruct.ster[3].var2 = new float[3]; // Because I need 3 floats on each pack2
         mystruct.ster[0].var2[0] = 1F;
         mystruct.ster[0].var2[1] = 1F;
         mystruct.ster[0].var2[2] = 1F;
    } 

我希望对人们有用。感谢alex

1 个答案:

答案 0 :(得分:3)

您需要初始化数组。

// One instance
ster = new pack2[1];

您可以在阵列here上找到更多信息。

结构在实际代码中很少有用。大多数时候你应该使用课程。

有关何时使用结构(很少),请参阅此answer