簡體   English   中英

具有靜態類屬性的NullReferenceException

[英]NullReferenceException with static class property

我有一個看起來像這樣的靜態類:

namespace Argus
{
    static class Argus
    {
        public static List<Branch> myArgus;
    }
}

在我的代碼的其他地方,我有這個:

// Add this branch to myArgus
Argus.myArgus.Add(branch);

運行代碼時,出現以下錯誤:

你調用的對象是空的。

我已經驗證了branch是有效的(它是Branch類的對象),並且不知道這里可能有什么問題。 我正在嘗試從文本文件中讀取分支數據。

您需要實例化它。 它的默認值為null,否則:

public static List<Branch> myArgus = new List<Branch>();

您必須實例化myArgus

public static List<Branch> myArgus = new List<Branch>();

您永遠不會為myArgus分配內存。 當然是null

public static List<Branch> myArgus = new List<Branch>();

您必須始終使引用指向內存中已分配的對象,否則無法使用它們。 嘗試對未指向分配的內存的引用調用操作將導致NullPointerException

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM