Skip to content

Instantly share code, notes, and snippets.

@yhstvhd
Last active August 31, 2019 14:56
Show Gist options
  • Save yhstvhd/79b64dc05d8db4358b2355cd3aec9239 to your computer and use it in GitHub Desktop.
Save yhstvhd/79b64dc05d8db4358b2355cd3aec9239 to your computer and use it in GitHub Desktop.
C# インデクサと「オブジェクト参照がオブジェクト インスタンスに設定されていません。」について

C# インデクサと「オブジェクト参照がオブジェクト インスタンスに設定されていません。」について

{get; set;}を使いたいだけなのに....。

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


class InfomationCollections
{
	public List<string> Titles { get; set; } 
	public List<string> WeekDays { get; set; }
	public List<string> StartTime { get; set; }	
	public List<string> 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