Skip to content

Instantly share code, notes, and snippets.

@yhstvhd
Created January 9, 2018 15:19
Show Gist options
  • Save yhstvhd/86a4f7f8d895beff93ed2965363633b0 to your computer and use it in GitHub Desktop.
Save yhstvhd/86a4f7f8d895beff93ed2965363633b0 to your computer and use it in GitHub Desktop.
インデクサto

インデクサについて インデクサを2割ぐらいしか理解してない人が、壁にぶち当たったのでメモします。 (正直言ってあまりインデクサ関係ないかもしれないし、関係あるかもしれない...)

class InfomationCollections { public List Titles { get; set; } public List WeekDays { get; set; } public List StartTime { get; set; } public List OnAir { get; set; } }

まあこんな感じでList型のプロパティのインデクサを作りました。 ほなちょっこら他のクラスで使うか class hoge { public void hogehoge { InfomationCollections infCollections = new InfomationCollections();

	//TextFileAllReadの内容をInfomationCollectionsの各プロパティに選別、格納

	for (int i = 0 ; i < TextFileAllRead.Count; i += 4)
	{
		infCollections.Titles.Add(TextFileAllRead[i]);
		infCollections.WeekDays.Add(TextFileAllRead[i + 1]);
		infCollections.StartTime.Add(TextFileAllRead[i + 2]);
		infCollections.OnAir.Add(TextFileAllRead[i + 3]);
	}
}

}

まぁこんな感じだな。 ビルド&実行や

エラー:System.NullReferenceException: オブジェクト参照がオブジェクト インスタンスに設定されていません。[行:39]

なんでや!

要するに、エラーメッセージさんは「どっかでNullだから、new するとか値入れるとかしーや」と言っているようで...。

NullReferenceException?どこでNullってるんや!なんでや!とGoogle先生を問い詰めたところ...

同じような症状にあっている方がいらっしゃいました。 https://teratail.com/questions/48849

この方の質問と回答をまとめると、 インデクサのプロパティでも何でもnewしなきゃいけないものはいけないということらしいです。 ということで

class hoge { public void hogehoge { InfomationCollections infCollections = new InfomationCollections();

	//new しよう
	infCollections.Titles = new List<string>();
	infCollections.WeekDays = new List<string>();
	infCollections.StartTime = new List<string>();
	infCollections.OnAir = new List<string>();


	//TextFileAllReadの内容をInfomationCollectionsの各プロパティに選別、格納

	for (int i = 0 ; i < TextFileAllRead.Count; i += 4)
	{
		infCollections.Titles.Add(TextFileAllRead[i]);
		infCollections.WeekDays.Add(TextFileAllRead[i + 1]);
		infCollections.StartTime.Add(TextFileAllRead[i + 2]);
		infCollections.OnAir.Add(TextFileAllRead[i + 3]);
	}
}

}

以上です。

内容が間違っているかも(間違っていると思うので)ご指摘お願いします。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment