代码之家  ›  专栏  ›  技术社区  ›  Nathan

程序中出现System.NullReferenceException错误

  •  0
  • Nathan  · 技术社区  · 13 年前

    在我的程序中,我得到了错误:

    An unhandled exception of type 'System.NullReferenceException' occurred in POS    System.exe
    
    Additional information: Object reference not set to an instance of an object.
    

    当我试图向TransactionList添加一些内容时,就会发生这种情况,如下所示。TransactionList是类实例的列表,声明如下:

    public static List<Transaction> TransactionList { get; set; }

    这是Transaction类:

    class Transaction
    {
        public double TotalEarned { get; set; }
        public double TotalHST { get; set; }
        public double TotalCost { get; set; }
        public string Category { get; set; }
        public int DaysSince2013 { get; set; }
    }
    

    有什么线索吗?我似乎不明白为什么会出现这个错误。。。谢谢

    for (int i = 0; i < (lines / 5); i++)
            {
                TransactionList.Add(new Transaction //Error happens on this line
                {
                    TotalEarned = Convert.ToDouble(stringArray[(i * 5)]),
                    TotalCost = Convert.ToDouble(stringArray[(i * 5) + 1]),
                    TotalHST = Convert.ToDouble(stringArray[(i * 5) + 2]),
                    Category = stringArray[(i * 5) + 3],
                    DaysSince2013 = Convert.ToInt32(stringArray[(i * 5) + 4])
                });
            }
    
    3 回复  |  直到 13 年前
        1
  •  6
  •   gleng    13 年前

    只需在您的 for loop ?

    if (TransactionList == null)
       TransactionList = new List<Transaction>();
    
    for (int i = 0; i < (lines / 5); i++)
            {
                TransactionList.Add(new Transaction //Error happens on this line
                {
                    TotalEarned = Convert.ToDouble(stringArray[(i * 5)]),
                    TotalCost = Convert.ToDouble(stringArray[(i * 5) + 1]),
                    TotalHST = Convert.ToDouble(stringArray[(i * 5) + 2]),
                    Category = stringArray[(i * 5) + 3],
                    DaysSince2013 = Convert.ToInt32(stringArray[(i * 5) + 4])
                });
            }
    

    或者如果你不喜欢,因为你已经宣布了 static ,您可以执行以下操作:

    public static List<Transaction> TransactionList = new List<TransactionList>();
    
        2
  •  0
  •   Saranya    13 年前

    你必须 初始化列表 在使用它之前。当你得到对象引用没有设置为instance错误时,这意味着对象在物理上不存在

        3
  •  -2
  •   PauloHDSousa    13 年前

    TransactionList和或stringArray最好都为null。

    试着这样做

    公共静态列表TransactionList{get;set;}

    if(TransactionList  == null)
       TransactionList  = new List<Transaction>();
    
    推荐文章