2014-10-08 28 views
0

我在Shapes[0].DamageofShape[0] = 7;處收到空引用異常。我是否需要在某處進行另一次初始化?結構數組中的數組上的空引用異常

public struct TestArrayStruct 
    { 
     public int[] DamageofShape; 
    } 

class Program 
    { 

     static void Main(string[] args) 
     { 
      TestArrayStruct[] Shapes = new TestArrayStruct[5]; 

      Shapes[0].DamageofShape[0] = 7; 
     } 
    } 

回答

4

需要初始化Shapes[0].DamageofShape ,其值是null默認:

Shapes[0].DamageofShape = new int[4]; 

你可以在構造函數中執行這項作業:

public struct TestArrayStruct 
{ 
    public int[] DamageofShape; 

    public TestArrayStruct(int size) 
    { 
     this.DamageofShape = new int[size]; 
    } 
} 

然而,然後你必須實例化你的結構與構造函數利用它:

Shapes[0] = new TestArrayStruct(4); 
Shapes[0].DamageofShape[0] = 7; 


以前的版本,如果這個答案是說你有實例 Shapes[0],這是不正確的

+0

感謝。我還沒有寫出一年以上的結構,而且是基於視覺的,所以上下文略有不同。 – 2014-10-08 15:10:29