C#/C#200제

[C#] 10일차 - 69. 속성(Property)

반나무 2021. 1. 30. 15:21

필드를 public으로 선언하면 원치 않게 클래스 외부에서 값을 바꿀 수 있기 때문에 캡슐화 원칙에 위배 됩니다. 따라서 일반적으로 private로 선언하는데 이러면 외부에서 접근할 수 없으므로 public 메소드(getter, setter)를 사용해서 값을 가져오거나 바꿀 수 있게 합니다.

 

속성은 getter와 setter를 쉽게 만들 수있는 방법입니다.

 

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

namespace A069_Property
{
    class RectwithProp
    {
        // prop을 입력하고 tab두번 치면 자동완성됨
        public double Width { get; set; }
        public double Height { get; set; }
    }
    // 위보단 좀 길어지지만 if문등 다양한 세팅이 가능하다는 장점이있음
    class RectwithPropFull
    {
        private double width;
        public double Width
        {
            get { return width; }
            set { if (value > 0) width = value; }
        }
        private double height;
        public double Height
        {
            get { return height; }
            set { if (value > 0) height = value; }
        }
    }
    class PropertyTest
    {
        static void Main(string[] args)
        {
            RectwithProp r = new RectwithProp();
            r.Width = 10.0;
            r.Height = 10.0;
            Console.WriteLine("r의 면적은{0}", r.Width * r.Height);

            RectwithPropFull r2 = new RectwithPropFull();
            r2.Width = 10.0;
            r2.Height = -10.0;
            Console.WriteLine("r의 면적은{0}", r.Width * r2.Height);
        }
    }
}

반응형