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;
}
}
}
get 접근자: 필드 값을 반환.set 접근자: 필드 값을 설정.과거에는 Get/Set 메서드를 사용하여 값에 접근했습니다.
private int money;
// Getter 메서드
public int GetMoney()
{
return money;
}
// Setter 메서드
public void SetMoney(int value)
{
money = value;
}
✔️ 문제점
C#에서는 Property를 사용하여 더 간결한 코드 작성이 가능합니다.
private int money;
public int Money
{
get
{
return money;
}
set
{
money = value;
}
}
✔️ 개선점
giftBox.Money = 10; 처럼 필드에 직접 값을 설정하는 것처럼 보이지만, 내부적으로 set이 실행됨.Console.WriteLine(giftBox.Money); 처럼 값을 가져올 때 내부적으로 get이 실행됨.public int Money { get; set; }
✔️ 특징
private int money;를 자동 생성.get 또는 set을 제거하여 읽기 전용/쓰기 전용 프로퍼티를 만들 수 있음.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);를 호출하여 자동으로 출력.public int Money { get; private set; }
private set).