C#/수업 내용

[C#] 읽기/쓰기 get, set

JSH1 2021. 8. 30. 15:12
class App
{
    //생성자
    public App()
    {
        SCV scv = new SCV(100);

        scv.Hp = 50;
        Console.WriteLine("hp: {0}", scv.Hp);

        scv.Hp = -50;
        Console.WriteLine("hp: {0}", scv.Hp);
    }
}
class SCV
{
    private int hp;

    //get속성 접근자
    //set속성 접근자
    //<속성접근제한자> <반환타입> <속성이름>
    public int Hp
    {
        get
        {
            return this.hp;
        }
        set
        {
            if (value > 0)
            {
                this.hp = value;
            }
        }
    }

    //생성자
    public SCV(int hp)
    {
        this.hp = hp;
    }
}


class SCV
{
    private int hp;

    //get속성 접근자
    //set속성 접근자
    //<속성접근제한자> <반환타입> <속성이름>
    public int Hp // 자동구현속성
    {
        get;
        set;
    }

    //생성자
    public SCV(int hp)
    {
        this.Hp = hp;
    }
}


 

'C# > 수업 내용' 카테고리의 다른 글

[C#] 2021-08-30 배열 연습  (0) 2021.08.31
[C#] abstract, interface  (0) 2021.08.31
[C#] 구조체 struct  (0) 2021.08.30
[C#] 2021-08-30  (0) 2021.08.30
[C#] class 상속(parent, child), virtual, override  (0) 2021.08.29