2017-09-08 5 views
0

リストにレコードを追加する際に問題があります。これはオブジェクト 'TranchesDt'のパラメータです。リストのオブジェクトにレコードを追加するC#

public class TranchesDt 
{ 
    public List<startup> tranches {get; set;} 
    public List<reservation> reservations { get; set; } 
    public List<location> locations { 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; 
} 

は、と私は

System.NullReferenceException取得:オブジェクト参照がインスタンスに設定されていませんオブジェクト。

dt.tranches.Add(Parse11(lines [i])); 私の問題はどこにあり、どのように修正できますか?

+1

'dt.tranches'のように見えません。どうやら、コンストラクターの 'TranchesDt'がそれを設定すると期待していますが、明示的なコンストラクターがないので、そこに追加するか、TranchesDtインスタンスを作成した後にプロパティを設定する必要があります。 – GolezTrol

+0

TranchesDtのリストは初期化されていません。クラスのコンストラクターでは、何かを行うことができますthis.tranches = new list () – Luc

答えて

2

Listインスタンスを初期化することはないため、dt.tranchesはnullです。 (他の2つのリストisntancesなど)

TranchesDt dt = new TranchesDt(); 

dt.tranches = new List<startup>(); 
dt.reservations = new List<reservation>(); 
dt.locations = new List<location>(); 

後にこのコードの行を追加し、構文エラーを探してください。

+2

オブジェクト初期化構文を使用するか、 'TranchesDt'コンストラクターでこれを行うことをお勧めします。 –

+1

最良の方法は(あなたのロジックに応じて)TranchesDtのコンストラクタのリストを@Chris Pickfordのように初期化することです – Dimitri

関連する問題