0

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

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

这是事务类:

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

3 回答 3

6

只需在您的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>();
于 2013-10-24T18:22:29.803 回答
0

您必须在使用它之前初始化列表。当您得到 Object reference not set to an instnce 错误时,这意味着该对象物理上不存在

于 2013-10-24T18:24:21.997 回答
-2

可能 TransactionList 和/或 stringArray 都是空的。

尝试这样做

公共静态列表 TransactionList { 获取;放; }

if(TransactionList  == null)
   TransactionList  = new List<Transaction>();
于 2013-10-24T18:26:09.613 回答