添加到列表导致空引用

时间:2013-07-09 20:24:00

标签: c# list collections

我有一个类来模拟正在上传的CSV格式(我正在使用FileHelpers库):

[DelimitedRecord(",")]
public class CSVModel
{
    [FieldQuoted('"', QuoteMode.OptionalForBoth, MultilineMode.NotAllow)]
    public string Field1;
    [FieldQuoted('"', QuoteMode.OptionalForBoth, MultilineMode.NotAllow)]
    public string Field2;
}

然后我有一个类在逐行解析文件后显示上传结果:

public class UploadResult
{
    public List<CSVModel> InvalidField;
    public List<CSVModel> Valid;
}

我不会详细介绍如何实现FileHelpers,因为它一切正常 - 文件可以成功上传 - 只有在我尝试将CS​​V模型的实例添加到如下列表时才会中断:

public static UploadResult ProcessCSV(CSVModel[] records)
{
    UploadResult uploadResult = new UploadResult();

    for (int i = 1; i < records.Length; i++)
    {
        CSVModel csvModel = records[i];

        // check stuff

        uploadResult.Valid.Add(csvModel); // this is where it breaks
    }

    return uploadResult;
}

异常只给我一个null引用。我可能做错了什么?

编辑:当我调试时,当我尝试将其添加到列表中时,'csvModel'肯定不为空

2 个答案:

答案 0 :(得分:2)

Validnull,您必须对其进行初始化:

public class UploadResult
{
    public List<CSVModel> InvalidField = new List<CSVModel>();
    public List<CSVModel> Valid = new List<CSVModel>();
}

或通过构造函数:

public class UploadResult
{
    public UploadResult()
    {
        InvalidField =  new List<CSVModel>();
        Valid =  new List<CSVModel>();
    }
    public List<CSVModel> InvalidField;
    public List<CSVModel> Valid;
}

答案 1 :(得分:1)

您正在初始化UploadResult但不是List属性。尝试这样的事情:

UploadResult uploadResult = new UploadResult {
    InvalidField = new List<CSVModel>(),
    Valid = new List<CSVModel>()
};