유니티로 배우는 c#

인덱서

테오구 2021. 10. 10. 18:22
728x90
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Record
{
    public int[] temp = new int[5];
    // 인덱서 this는 해당 클래스를 지칭하는 예약어
    // this는 인덱서의 이름
    // int index로 매개변수를 받아줍니다.
    public int this[int index]
    {
        get {
            if(index >= temp.length)
            {
                Debug.Log("인덱스가 너무 큽니다.");
                return 0;
            }else
            {
                
            return temp[index]; }
            }
        // Record 클래스가 monoBehaviour를 상속받지 못하였기 때문에 print를 사용할 수 없습니다. 
        set { if (index >= temp.Length) Debug.Log("인덱스가 너무 큽니다."); else temp[index] = value;}
    }
}

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

    // Start is called before the first frame update
    void Start()
    {
        // 5는 set의 temp[index] = value;의 value로
        // [5]는 public int this[int index]의 index로 들어갑니다.
        record[3] = 1;
        record[5] = 5;

        print(record[3]);
        print(record[5]);
        // this.record this.record == record와 같은 의미
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}
728x90

'유니티로 배우는 c#' 카테고리의 다른 글

형식 매개 변수 T  (0) 2021.10.10
인터페이스  (0) 2021.10.10
프로퍼티  (0) 2021.10.10
상속  (0) 2021.10.10
델리게이트  (0) 2021.10.10