인덱서(Indexer)는 인덱스를 이용해서 객체 내의 데이터에 접근하게 해주는 프로퍼티이다. 

 

class 클래스이름
{
    한정자 인덱서형식 this[형식 index]
    {
        get
        {
            // index를 이용하여 내부 데이터 변환
        }
        set
        {
            // index를 이용하여 내부 데이터 저장
        }
    }
}

 

코드 예제)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Record
{
    public int[] temp = new int[5];

    public int this[int index]
    {
        get
        {
            if(index >= temp.Length)
            {
                Debug.Log("인덱스가 너무 큽니다.");
                return 0;
            }
            else
            {
                return temp[index];
            }            
        }
        set
        {
            if(index >= temp.Length)
            {
                Debug.Log("인덱스가 너무 큽니다.");
            }
            else
            {
                temp[index] = value;
            }
        }
    }
}

public class Test : MonoBehaviour
{
    void Start()
    {
        Record record = new Record();
        record[3] = 5;
        record[5] = 5;
    }
}

 

출력 결과: 

'프로그래밍 언어 > C#' 카테고리의 다른 글

C# 람다식  (0) 2019.12.05
C# 형식 매개변수 T  (0) 2019.12.05
C# 프로퍼티  (0) 2019.12.05
C# 상속  (0) 2019.12.05
C# 델리게이트와 이벤트  (0) 2019.12.05
Posted by 소블리애
,