2010-09-16 120 views
2

使用NUnit測試用下面的代碼塊C#代碼:空對象引用

foreach (XmlNode node in nodeList) 
{ 
    thisReport.Id = node.Attributes.GetNamedItem("id").Value; 
    thisReport.Name = node.Attributes.GetNamedItem("name").Value; 
    thisReport.Desc = node.Attributes.GetNamedItem("desc").Value; 
    if (node.SelectNodes("subreport").Count > 0) 
    { 
     thisReport.HasSubReport = true; 
     subReportNodeList = node.SelectNodes("subreport"); 
     foreach(XmlNode subNode in subReportNodeList) 
     { 
      mySubReport.ParentID = node.Attributes.GetNamedItem("id").Value; 
      mySubReport.Priority = subNode.Attributes.GetNamedItem("priority").Value; 
      mySubReport.SubReportId = subNode.Attributes.GetNamedItem("id").Value; 
      mySubReport.SubReportName = subNode.Attributes.GetNamedItem("name").Value; 
      string sTime = subNode.Attributes.GetNamedItem("time").Value; 
      mySubReport.Time = Convert.ToInt16(sTime); 
      thisReport.SubReportsList.Add(mySubReport); 
     } 
    } 
    else 
    { 
     thisReport.HasSubReport = false; 
    } 
    reports.Add(thisReport); 
} 

的代碼失敗就行了空對象引用:

  thisReport.SubreportsList.Add(mySubReport) 

但看當地人, thisReport存在並且具有在塊頂部分配的值,並且存在mySubReport並且其值被添加到thisReport的行的上方。 mySubReport中的所有值都是有效的,SubReportsList中的thisReportSubReport類型的通用列表。

那麼,零位在哪裏呢?這看起來很簡單,它一定是我看不到的真正明顯的東西。

+2

如果'thisReport.SubReportsList.Add(mySubReport);'和'thisReport'和'mySubReport'中出現異常,那麼唯一的選擇是'thisReport.SubReportsList'爲null。仔細檢查你的財產實施。 – dtb 2010-09-16 15:02:07

+0

[在.NET中是什麼是NullReferenceException?]的可能重複(http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-in-net) – 2012-05-28 12:58:15

回答

1

它必須是SubReportsList然後是null。

2

你可能應該先做到:

thisReport.SubReportsList = new List<SubReport>(); 
0

確保使用new關鍵字來初始化列表。否則,列表本身將爲空。

5

在調用Add之前,您尚未實例化SubReportsList。加入mySubReport之前做到以下幾點:

thisReport.SubReportsList = new List<SubReport>(); 
thisReport.SubReportsList.Add(mySubReport); 

你也可以改變你的SubReportsList屬性,以使您的生活更輕鬆:

public class Report 
{ 
    public IList<SubReport> SubReportsList 
    { 
     get 
     { 
      if (_subReportsList == null) 
      { 
       _subReportsList = new List<SubReport>(); 
      } 
      return _subReportsList; 
     } 
    } 
    private IList<SubReport> _subReportsList; 
} 

這樣做會實例化你的清單,如果這就是所謂的,而它的空。

1

thisReport.SubReportsList是你的空引用;你已經聲明瞭它,但沒有初始化它。您可以在構造函數thisReport的類型中初始化它(可能使用新實例),或者在開始向它添加事件之前對其進行初始化。

1

作爲@GenericTypeTea和@Dan Dumitru已經提供了很好的答案我只是補充說,如果在調用屬性時該值爲null,則可以通過添加隱式構造來「自動」執行此操作。你可以,如果你不使用自動屬性ALA做到這一點:

public class Report { 
// ... other code ... 
private List<SubReports> _subReports = null; 

public List<SubReport> SubReports { 
    get { 
     if (_subReports == null) { _subReports = new List<SubReports>(); } 
     return _subReports; 
    } 
} 
} 

有一些注意事項需要注意,像使它線程安全的(這是現成的,袖口),但基本實現將爲你工作。我會小心使用這個設計,因爲它可以通過檢查屬性來創建你不一定需要的對象。如果這是不可取的,那麼堅持上面推薦的實現。