程序中的System.NullReferenceException错误

时间:2013-10-24 18:20:09

标签: c# .net winforms exception visual-studio-2012

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

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 个答案:

答案 0 :(得分: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>();

答案 1 :(得分:0)

在使用之前,您必须初始化列表。如果未将对象引用设置为实例错误,则表示该对象在物理上不存在

答案 2 :(得分:-2)

可行的TransactionList和/ stringArray都是null。

尝试这样做

public static List TransactionList {get;组; }

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