백지부터 시작하는 이세계 코딩 생활

Property, Attribute (속성) 본문

백지부터 시작하는 이세계 유니티 생활 since 2020

Property, Attribute (속성)

조아덕 2020. 12. 9. 18:42
Property (Attribute)

속성 (Attrubute) 이란 특정 필드의 값에 접근(GET) 하거나 값을 설정(SET) 하는 매서드 (Method).
private 으로 선언된 맴버에 대해 접근이나 설정을 위해 사용한다.
속성에는 get 접근자와 (GET Accessor) set 접근자 (SET Accessor)가 존재한다.

속성을 이용하면 필드 공개 수준을 다양하게 처리할 수 있다.

using UnityEngine;

public class Human
{
    public string name;
    public int age;
    public float tall;

    public string GetName()
    {
        return name;
    }

    public void SetName(string _name)
    {
        this.name = _name;
    }

    public int GetAge()
    {
        return age;
    }

    public void SetAge(int _age)
    {
        this.age = _age;
    }

    public float GetTall()
    {
        return tall;
    }

    public void SetTall(float _tall)
    {
        this.tall = _tall;
    }
}
using UnityEngine;

public class Property : MonoBehaviour
{
    private void Start()
    {
        Human H = new Human("JJOA", 201210, 1656);

        //GET
        #region GET DATA
        int getAge = H.GetAge();
        print("this is Property class, getAge : " + getAge);

        string getName = H.GetName();
        print("this is Property class, getName : " + getName);

        float getTall = H.GetTall();
        print("this is Property class, getTall : " + getTall);
        #endregion

        #region SET DATA and CHECK set data
        // SET
        H.SetAge(1700);
        H.SetName("Duck");
        H.SetTall(2012.10f);

        int SetAge = H.GetAge();        
        print("this is Property class, SetAge : " + SetAge);

        string SetName = H.GetName();        
        print("this is Property class, SetName : " + SetName);

        float SetTall = H.GetTall();        
        print("this is Property class, SetTall : " + SetTall);
        #endregion
    }
}

 

Result :

Human class 멤버에 Get으로 접근하여 확인 --> Set 으로 값 수정 --> console창에서 변화된 값 확인.

Comments