1

我有一个模拟上传的 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,因为它一切正常 - 文件可以成功上传 - 只有当我尝试将 CSV 模型的实例添加到这样的列表时才会中断:

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

例外只是给我空引用。我可能做错了什么?

编辑:当我调试时,当我尝试将它添加到列表时,'csvModel' 绝对不为空

4

2 回答 2

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;
}
于 2013-07-09T20:25:52.760 回答
1

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

UploadResult uploadResult = new UploadResult {
    InvalidField = new List<CSVModel>(),
    Valid = new List<CSVModel>()
};
于 2013-07-09T20:26:42.467 回答