2013-08-24 95 views
3

我是編程的新手,尤其是在c#中。我編寫了一些代碼,但運行時一直收到錯誤,直到修復完成後才能繼續。遇到問題NullReferenceException

有問題的錯誤是NullReferenceException。它還告訴我「對象引用未設置爲對象的實例」。

這似乎是一個非常明確的錯誤消息,指示對象尚未實例化。但是我認爲我已經做到了。我希望有人能向我解釋我做錯了什麼。這是我的代碼。

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.IO; 

namespace EvenHelemaalOvernieuw 
{ 
    class Globals 
    { 
     public static int size = 50; 
     public static int factor = 3; 
     public static int puzzleNumber = 1; 
     public static Square[,] allSquares = new Square[Globals.factor * Globals.factor, Globals.factor * Globals.factor]; 
     public static String path = @"" + factor.ToString() + "\\" + puzzleNumber.ToString() + ".txt"; 
     public static int[,][,] values = new int[factor, factor][,]; 

     public Globals() { } 

     public void setSize(int s) 
     { 
      size = s; 
      if (size > 100) 
      { 
       size = 100; 
      } 
      if (size < 20) 
      { 
       size = 20; 
      } 
     } 

     public void setFactor(int f) 
     { 
      factor = f; 
      if (factor > 5) 
      { 
       factor = 5; 
      } 
      if (factor < 2) 
      { 
       factor = 2; 
      } 
     } 

     public Square getSquare(int x, int y) 
     { 
      return allSquares[x, y]; 
     } 

     public static void readPuzzle() 
     { 
      List<int> conversion = new List<int>(); 
      int count = 0; 
      using (StreamReader codeString = new StreamReader(path)) 
      { 
       String line = codeString.ReadToEnd(); 
       Array characters = line.ToCharArray(); 
       foreach (char a in characters) 
       { 
        if (a.ToString() != ",") 
        { 
         conversion.Add(Convert.ToInt32(a)); 
        } 
       } 
       for (int panelX = 0; panelX < factor; panelX++) 
       { 
        for (int panelY = 0; panelY < factor; panelY++) 
        { 
         for (int squareX = 0; squareX < factor; squareX++) 
         { 
          for (int squareY = 0; squareY < factor; squareY++) 
          { 
           values[panelX, panelY][squareX, squareY] = conversion[count]; 
           count++; 
          } 
         } 
        } 
       } 
      } 
     } 
    } 
} 

錯誤消息指示的行接近底部並且顯示爲values[panelX, panelY][squareX, squareY] = conversion[count];

+0

你的樣品初始化缺少代碼只是初始化數組元素'值[panelX,panelY]' - 請張貼那部分。 –

+1

你已經理解了這個消息並且分析了一下這個問題。看到一個問題在哪裏完成,真是令人耳目一新。 +10 – usr

+0

幾乎所有的'NullReferenceException'都是一樣的。請參閱「[什麼是.NET一個NullReferenceException?](http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net)」獲得一些提示。 –

回答

6

的問題是以下行

public static int[,][,] values = new int[factor, factor][,]; 

這是一個數組的數組但是這個代碼僅創建外陣列。內部陣列未初始化,將爲null。下面的代碼運行因此,當它會拋出一個NullReferenceException試圖訪問內陣列

values[panelX, panelY][squareX, squareY] = conversion[count]; 

爲了解決這個問題的第三個嵌套循環前右

values[panelX, panelY] = new int[factor, factor]; 
for (int squareX = 0; squareX < factor; squareX++) 
+0

這個伎倆!謝謝你的幫助。我的代碼沒有達到我期望的效果,但至少現在我可以看到發生了什麼並嘗試修復。 – Rainier