최근에 c#의 문법 중 Indexer (인덱서) 라고 하는 친구의 존재를 알게 되었습니다. 그래서 Indexer는 어떤식으로 사용할 수 있을지 생각해보다가 특정 클래스 안에 딕셔너리가 있고 그 딕셔너리를 public으로 직접 접근하지않고 Indexer로 딕셔너리의 Value값을 접근하는 것을 생각해보았습니다.
간략하게 인덱서의 문법을 설명해드리자면,
public T this[int i] => arr[i];
이런식으로 쓰이게 됩니다. 다른 클래스에서 접근할 때에는 해당 클래스 이름 뒤에 [파라미터 값] 을 넣어서 접근을하게됩니다.
예제로 Monster와 MonsterCollection이라는 클래스가 존재하고, MonsterCollection 클래스 안에는 Monster의 이름(string)을 Key값으로 가지고 Monster 타입을 Value 타입으로 가지는 monsterCollection 딕셔너리가 있습니다.
using System;
using System.Collections.Generic;
namespace ForBlog
{
	namespace Indexer 
	{
		class MonsterCollection
		{
			private Dictionary<string, Monster> monsterCollection = new Dictionary<string, Monster>();
			public Monster this[string name] => monsterCollection[name];
			public void Add(Monster newMonster)
			{
				if(monsterCollection.ContainsKey(newMonster.name))
				{
					Console.WriteLine("monster with name [{0}] already exists in the collection", newMonster.name);
					return; 
				}
				monsterCollection.Add(newMonster.name, newMonster);
			}
			public void MonsterInfo(Monster reqMonster)
			{
				if(monsterCollection.ContainsKey(reqMonster.name))
				{
					Monster monster = this[reqMonster.name];
					Console.WriteLine("Monster Name : [{0}] / Type : [{1}]", monster.name, monster.type.ToString());
				}
				else
				{
					Console.WriteLine("No such monster exists");
				}
			}
			public void ListOutMonsters()
			{
				Console.WriteLine("List of Monsters : ");
				foreach(var monster in monsterCollection)
				{
					Console.Write(monster.Key + " ");
				}
			}
		}
		class Monster
		{
			public string name { get; private set; }
			public MonsterType type { get; private set; }
			public Monster(string name, MonsterType type)
			{
				this.name = name;
				this.type = type;
			}
		}
		public enum MonsterType { Good, Bad}
	}
	
}
MonsterCollection 클래스에서
public Monster this[string name] => monsterCollection[name];
이 부분이 인덱서를 사용해서 string 값을 파라미터로 받아서 딕셔너리의 Value 값을 가지고 오는 부분입니다.
콘솔 프로그램에서 한번 실행하는 코드를 아래와 같이 작성했습니다.
using System;
namespace ForBlog
{
	namespace Indexer
	{
		class Program
		{
			static void Main(string[] args)
			{
				MonsterCollection monsterCollection = new MonsterCollection();
				monsterCollection.Add(new Monster("loki", MonsterType.Bad));
				monsterCollection.Add(new Monster("pikachu", MonsterType.Good));
				monsterCollection.Add(new Monster("Spiderman", MonsterType.Good));
				monsterCollection.ListOutMonsters();
				AddLineBreak(2);
				Console.WriteLine("Select Monster :");
				string selected = Console.ReadLine();
				Monster selectedMonster = monsterCollection[selected];
				monsterCollection.MonsterInfo(selectedMonster);
			}
			private static void AddLineBreak(int numOfLines = 1)
			{
				for(int i=0; i< numOfLines;i++)
				{
					Console.WriteLine("");
				}
			}
		}
	}
}
콘솔 프래그림을 실행시키고 "loki"라는 몬스터를 입력했을 때 인덱서를 사용해서 Monster 를 가지고 올 수 있었습니다

이번 예제에선 string을 파라미터로 활용하는 인덱서였는데 "인덱서"라는 이름대로 int값을 받는 인덱서로 배열이나 리스트에서 값들을 가지고 올 수 있게 자주 활용 할 수 있을 것 같네요
'Unity & C#' 카테고리의 다른 글
| [유니티] Unity Profiler 사용하기 (0) | 2022.07.05 | 
|---|---|
| [C#] Switch문을 사용한 Type Pattern Matching (0) | 2022.06.26 | 
| CustomEditor 활용하기 - Inspector Button만들기 (0) | 2022.04.06 | 
| CustomEditor 활용하기 - bool 값으로 variable 보여주기 (0) | 2022.04.03 | 
| [유니티] 왜 이제 알았을까 요놈 Animation Curve (2) | 2021.12.16 |