51. 인덱서(Indexer)
==> 인덱서.cs
using System;
public class 인덱서
{
public static void Main()
{
#region Car
Car hyundai = new Car(3);
hyundai[0] = "에쿠스";
hyundai[1] = "소나타";
hyundai[2] = "산타페";
for (int i = 0; i < hyundai.Length; i++)
{
Console.WriteLine(hyundai[i]);
}
#endregion
Person saram = new Person();
// 문자열 인덱서
saram["닉네임"] = "RedPlus";
saram["주소"] = "Incheon";
Console.WriteLine(saram["닉네임"]);
Console.WriteLine(saram["주소"]);
}
}
==============================================================================================
==> Car.cs
using System;
//[1] Class
public class Car
{
//[2] Property
public int Length { get; set; }
//[3] Constructor
public Car()
{
// Empty
}
public Car(int length)
{
this.Length = length;
catalog = new string[length]; // 요소수 생성
}
//[4] Field
private string[] catalog; // 배열 생성
//[5] Indexer
public string this[int index]
{
get { return catalog[index]; }
set { catalog[index] = value; }
}
}
==============================================================================================
==> Person.cs
using System;
using System.Collections;
public class Person
{
//[1] 문자열 인덱서
public string this[string index]
{
get { return (string)names[index]; }
set { names[index] = value; }
}
//[2] Key/Value 저장 필드
Hashtable names = new Hashtable();
}