Unity C# 인덱서 Indexer

Intro

C# 인덱서

인덱서

인덱서는 인덱스를 이용해 객체 내의 데이터에 접근할 수 있는 프로퍼티이다. 객체를 배열처럼 이용할 수 있다.

인덱서 사용

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

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

    public int this[int index]
    {
        get { return temp[index];}
        set { temp[index] = value; }
    }
}

public class Indexer : MonoBehaviour
{
    Record record = new Record();

    void Start()
    {
        record[4] = 5;
        print( record[4] );
    }
}

temp 배열의 크기가 5이므로 index에 5이상의 값이 오면 오류가 발생하기 때문에 get과 set앞에 다음과 같은 조건문을 추가함으로써 오류를 방지할 수 있다.

if(index >= temp.Length) Debug.Log("인덱스 초과");

참고자료

https://youtu.be/1sHa0NVfTcE?list=PLUZ5gNInsv_O7XRpaNQIC9D5uhMZmTYAf

태그: ,

카테고리:

업데이트:

댓글남기기