C# 将记录添加到列表c的对象#

C# 将记录添加到列表c的对象#,c#,list,parsing,object,C#,List,Parsing,Object,我在向列表中添加记录时遇到问题,该记录是对象“TranchesDt”的参数 public class TranchesDt { public List<startup> tranches {get; set;} public List<reservation> reservations { get; set; } public List<location> locations { get; set; } } public class

我在向列表中添加记录时遇到问题,该记录是对象“TranchesDt”的参数

public class TranchesDt
{
    public List<startup> tranches {get; set;}
    public List<reservation> reservations { get; set; }
    public List<location> locations { get; set; }
}
public class TranchesDt
{
公共列表部分{get;set;}
公共列表保留{get;set;}
公共列表位置{get;set;}
}
下面是代码,我将对象添加到“TranchesDt”:

public static TranchesDt Parse(string filePath)
{
    string[] lines = File.ReadAllLines(filePath);
    TranchesDt dt = new TranchesDt();

    for (int i = 0; i < lines.Length; i++)
    {
        string recordId = lines[i].Substring(0, 2);

        switch (recordId)
        {
            case "11":
                {
                    dt.tranches.Add(Parse11(lines[i]));
                    break;
                }
            case "01":
                {
                    dt.locations.Add(Parse01(lines[i]));
                    break;
                }
            case "00":
                {
                    dt.reservations.Add(Parse00(lines[i]));
                    break;
                }
        }
    }
    return dt;
}

public static startup Parse11(string line)
{
    var ts = new startup();
    ts.code = line.Substring(2, 5);
    ts.invoice = line.Substring(7, 7);
    ts.amount = Decimal.Parse(line.Substring(14, 13));
    ts.model = line.Substring(63, 4);
    ts.brutto = Decimal.Parse(line.Substring(95, 13));

    return ts;
}
公共静态TranchesDt解析(字符串文件路径)
{
string[]lines=File.ReadAllLines(文件路径);
TranchesDt=新的TranchesDt();
对于(int i=0;i
我得到

System.NullReferenceException:对象引用未设置为对象的实例

在dt.tranches.Add行(第11行(第[i]行));
我的问题在哪里?如何解决它?

您从不初始化列表实例,因此dt.tranches为空。(与其他两个列表相同)

在后面添加这行代码

TranchesDt dt = new TranchesDt();

dt.tranches  = new List<startup>();
dt.reservations = new List<reservation>();
dt.locations = new List<location>();
TranchesDt=新的TranchesDt();
dt.tranches=新列表();
dt.reservations=新列表();
dt.locations=新列表();

注意语法错误。

您从不初始化列表实例,因此dt.tranches为空。(与其他两个列表相同)

在后面添加这行代码

TranchesDt dt = new TranchesDt();

dt.tranches  = new List<startup>();
dt.reservations = new List<reservation>();
dt.locations = new List<location>();
TranchesDt=新的TranchesDt();
dt.tranches=新列表();
dt.reservations=新列表();
dt.locations=新列表();

注意语法错误。

看起来像是
dt。未设置档位。显然,您希望构造函数
TranchesDt
设置它,但是没有显式的构造函数设置它,因此您需要在那里添加它,或者在创建TranchesDt实例后自己设置属性。TranchesDt中的列表没有初始化。在类的构造函数中,您可以执行以下操作:this.tranches=new list()看起来像
dt。未设置tranches
。显然,您希望构造函数
TranchesDt
设置它,但是没有显式的构造函数设置它,因此您需要在那里添加它,或者在创建TranchesDt实例后自己设置属性。TranchesDt中的列表没有初始化。在类的构造函数中,您可以这样做。tranches=new list()使用对象初始值设定项语法,或者更好地在
TranchesDt
构造函数中这样做。最好的方法是(根据您的逻辑)在TranchesDt的构造函数中初始化列表,如@Chris Pickford提到的使用对象初始值设定项语法,或者最好在
TranchesDt
构造函数中执行此操作。最好的方法是(根据您的逻辑)初始化TranchesDt构造函数中的列表,如@Chris Pickford所述