System.NullReference程序中的异常错误

本文关键字:异常 错误 NullReference 程序 System | 更新日期: 2023-09-27 18:36:50

在我的程序中,我收到错误:

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 是一个类实例的列表,声明如下:

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

这是事务类:

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])
            });
        }

System.NullReference程序中的异常错误

只需在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>();
您必须在使用

列表之前启动列表。当您将对象引用未设置为instence错误时,这意味着该对象在物理上不存在

Proprable TransactionList 和 或 stringArray 都是空的。

尝试这样做

public static List TransactionList { get; set; }

if(TransactionList  == null)
   TransactionList  = new List<Transaction>();