C#/Basics

Class. 속성

페프 2021. 4. 25. 20:48
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _05_Property
{
    class Rect
    {
        /* public int Width { get; set; }*/ //prop 탭 두 번 >> 속성을 쓰는 것이 훨씬 간단하다. 
        private int width;

        public int Width
        {
            get { return width; }
            set { if(width>=0) width = value;
                else Console.WriteLine("width는 0보다 커야합니다.");
            }
        }


        private int height; //proopfull 탭 두 번 

        public int Height
        {
            get { return height; }
            set { if(value>=0) height = value;
                else Console.WriteLine("Height는 0보다 커야합니다.");
            }
        }

        public double GetArea()
        {
            return width * height;
        }

    }
    class Rectangle
    {
        private double width;
        private double height;


        public void SetWidth(int x)
        {
            if (x >= 0)
                this.width = x;
            else
                Console.WriteLine("width는 0보다 크거나 같아야합니다.");
        }
        public double GetWidth()
        {
            return this.width;
        }
        public void SethHeight(int x)
        {
            if (x >= 0)
                this.height = x;
            else
                Console.WriteLine("width는 0보다 크거나 같아야합니다.");
        }
        public double GetHeight()
        {
            return this.height;
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Rectangle x = new Rectangle();
            x.SetWidth(10);
            Console.WriteLine("Width = {0}", x.GetWidth());

            Rect y = new Rect();
            y.Width = 10;
            y.Height = -10;
            Console.WriteLine("width = {0}, height = {1}", y.Width,y.Height);
            Console.WriteLine("Area = {0}", y.GetArea());
        }
    }
}