Unity C# 프로퍼티 Property

Intro

C# 프로퍼티

프로퍼티

변수를 읽거나 때 프로퍼티를 이용하면 따로 메소드를 구현하지 않아도 간단하게 정보은닉을 위한 접근을 사용 할 수 있다.

예시

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

public class Property : MonoBehaviour
{

    private int salary;

    public int SalaryP { get { return salary; } private set { salary = value; } }

    
    void Start()
    {
        SalaryP = 50;

        print(SalaryP);
    }


}

Salary 프로퍼티의 set 앞에 private 를 붙여 다른클래스에선 읽기만 가능하고 쓰기가 불가능하도록 했다.

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

public class Employee : MonoBehaviour
{

    Property property = new Property();

    void Start()
    {
        property.SalaryP = 30; // 액세스 오류

        print(property.SalaryP);
    }

}

다른 클래스에서 SalaryP에 쓰기를 시도할경우 액세스 오류가 발생하며 값을 가져오는데에는 문제가 없는것을 확인할 수 있다.

간단한 프로퍼티

public float HP { get; set; }

변수 선언과 프로퍼티를 같이 사용할 수 있다.

참고자료

https://youtu.be/omLAXfibAwg?list=PLUZ5gNInsv_O7XRpaNQIC9D5uhMZmTYAf

태그: ,

카테고리:

업데이트:

댓글남기기