전체 코드

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GiftBoxNamespace
{
    class GiftBox
    {
        // 바로 사용
        // 컴파일러가 private 변수 만들어줌
        public string Letter { get; set; }
        //확장 가능하지만 private 변수를 만들어줘야함
        

        // 외부에서 접근하지 못하게 하려면
        private int money;

        // 외부에서 사용하게 하는 방법
        // 1. getter setter 문법
        public int GetMoney() { return money; }

        public void SetMoneyMag(int value)
        {
            money = value * 10000;
        }

        // property
        public int Money
        {
            get
            {
                return money;
            }
            set
            {
                money = value;
            }
        }

        public ITEM_GRADE Grade; // 유니크아이템, 레어아이템, 노멀아이템
    }
}
using GiftBoxManagerNamespace;
using GiftBoxNamespace;
using System;
using System.Collections;
using System.ComponentModel;
using System.Text;

namespace C_
{

    class Program
    {
        static GiftBox giftBox = new GiftBox();
        static void Main(string[] args)
        {
            GiftBox giftBox = new GiftBox();
            giftBox.SetMoneyMag(10);

            // property
            giftBox.Money = 10;

        }


    }
}

1. 프로퍼티(Property)란?

  • C#에서 프로퍼티(Property) 는 필드(Field)와 메서드(Method)의 조합으로,
    필드 값을 안전하게 접근하고 변경할 수 있도록 하는 기능입니다.
  • get 접근자: 필드 값을 반환.
  • set 접근자: 필드 값을 설정.

2. 기본적인 Getter, Setter

과거에는 Get/Set 메서드를 사용하여 값에 접근했습니다.

private int money;

// Getter 메서드
public int GetMoney()
{
    return money;
}

// Setter 메서드
public void SetMoney(int value)
{
    money = value;
}

✔️ 문제점

  • 매번 메서드를 호출해야 하므로 코드가 길어짐.
  • 직접적인 값 변경이 어려움.

3. Property를 사용한 Getter, Setter

C#에서는 Property를 사용하여 더 간결한 코드 작성이 가능합니다.

private int money;

public int Money
{
    get 
    { 
        return money; 
    }
    set 
    { 
        money = value;
    }
}

✔️ 개선점

  • giftBox.Money = 10; 처럼 필드에 직접 값을 설정하는 것처럼 보이지만, 내부적으로 set이 실행됨.
  • Console.WriteLine(giftBox.Money); 처럼 값을 가져올 때 내부적으로 get이 실행됨.

4. 자동 구현 프로퍼티 (Auto-Implemented Property)

public int Money { get; set; }

✔️ 특징

  • 컴파일러가 private int money;를 자동 생성.
  • 간단한 Getter/Setter를 사용할 때 유용.
  • 필요에 따라 get 또는 set을 제거하여 읽기 전용/쓰기 전용 프로퍼티를 만들 수 있음.

5. Property를 활용한 추가 기능

Property를 사용하면 값을 설정할 때 로직을 추가할 수 있음.

private int money;
public int Money
{
    get 
    { 
        return money; 
    }
    set 
    { 
        money = value * 10000; // 값 변경 시 연산 추가
        PrintMoney(money);
    }
}

private void PrintMoney(int money)
{
    Console.WriteLine($"현재 Money 값: {money}");
}

✔️ 개선점

  • giftBox.Money = 10; 하면 자동으로 value * 10000 계산.
  • 값을 설정할 때 PrintMoney(money);를 호출하여 자동으로 출력.

6. 읽기 전용 (Read-Only) 프로퍼티

public int Money { get; private set; }
  • 외부에서는 값을 읽을 수만 있고, 변경은 불가능 (private set).
  • 생성자에서만 값 설정 가능.

profile
李家네_공부방

0개의 댓글