C#

49.C# - Indexer (인덱서)

Godffs 2009. 8. 12. 21:09
반응형
인덱서 란 배열과 같은 방식으로 { } 사이에 값을 지정해서 사용하는 속성입니다.
속성과 다른점은 인덱서는 접근자에 매개 변수가 있습니다.

 Indexer.cs
using System;

public class Indexer
{
    public static void Main(string[] args)
    {
        #region Car
        Car hyundai = new Car(3);  //생성자 필요


        hyundai[0] = "에쿠스"; //인덱서 필요
        hyundai[1] = "소나타";
        hyundai[2] = "산타페";

        for (int i = 0; i < hyundai.Length; i++) //Length 속성 필요
        {
            Console.WriteLine(hyundai[i]);
        }
        #endregion


        Person saram = new Person();
        // 문자열 인덱서 : 속도는 떨어지지만 편리함
        saram["닉네임"] = "RedPlus";
        saram["주소"] = "Seoul";

        Console.WriteLine(saram["닉네임"]);
        Console.WriteLine(saram["주소"]);
    }
}

 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();
}

Car.cs
using System;
//[1] Class
public class Car
{
    //[2] Property : prop
    public int Length { get; set; }
    //[3] Constructor : ctor
    public Car()
    {
        // Empty
    }
    public Car(int length)
    {
        this.Length = length;
        catalog = new string[length]; // 요소수 생성
    }
    //[4] Field
    private string[] catalog; // 배열 생성
    //[5] Indexer : index
    public string this[int index]
    {
        get { return catalog[index]; }
        set { catalog[index] = value; }
    }
}
반응형