C# Methods and Properties


메서드 및 속성 (Methods and Properties)

메서드와 속성 소개 (Introduction to Methods and Properties)

메서드와 속성은 C# 클래스의 기본 구성 요소입니다. 메서드는 클래스의 동작을 정의하며, 속성은 클래스의 데이터를 정의하고 접근하는 방법을 제공합니다. C#의 메서드와 속성은 객체 지향 프로그래밍의 핵심 개념으로, 코드의 재사용성과 가독성을 높여줍니다.

메서드 정의 및 호출 (Defining and Calling Methods)

메서드는 특정 작업을 수행하는 코드 블록입니다. 메서드는 클래스 내에서 정의되며, 메서드를 호출하여 작업을 수행할 수 있습니다.

예제: 메서드 정의 및 호출 (Defining and Calling a Method)

using System;

namespace MethodExample
{
    class Calculator
    {
        // 메서드 정의 (Defining a Method)
        public int Add(int a, int b)
        {
            return a + b;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Calculator calculator = new Calculator();
            int result = calculator.Add(5, 3); // 메서드 호출 (Calling a Method)
            Console.WriteLine("Sum: " + result);
        }
    }
}

이 예제에서 Calculator 클래스는 Add 메서드를 정의하여 두 숫자의 합을 반환합니다. Program 클래스에서 Calculator 객체를 생성하고 Add 메서드를 호출하여 결과를 출력합니다.

메서드 매개변수 및 반환 값 (Method Parameters and Return Values)

메서드는 매개변수를 받아 작업을 수행하고, 결과를 반환할 수 있습니다. 매개변수는 메서드 호출 시 전달되는 입력 값이며, 반환 값은 메서드 실행 후 돌려주는 결과입니다.

예제: 매개변수와 반환 값을 사용하는 메서드 (Methods with Parameters and Return Values)

using System;

namespace MethodExample
{
    class Calculator
    {
        public int Multiply(int a, int b)
        {
            return a * b;
        }

        public double Divide(double a, double b)
        {
            if (b == 0)
            {
                throw new DivideByZeroException("Divisor cannot be zero.");
            }
            return a / b;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Calculator calculator = new Calculator();
            int product = calculator.Multiply(4, 5);
            Console.WriteLine("Product: " + product);

            try
            {
                double quotient = calculator.Divide(10, 2);
                Console.WriteLine("Quotient: " + quotient);
            }
            catch (DivideByZeroException e)
            {
                Console.WriteLine(e.Message);
            }
        }
    }
}

이 예제에서 Multiply 메서드는 두 숫자를 곱한 값을 반환하고, Divide 메서드는 두 숫자를 나눈 값을 반환합니다. Divide 메서드는 0으로 나누는 경우 예외를 발생시킵니다.

속성 (Properties)

속성은 클래스의 데이터를 읽고 쓸 수 있는 방법을 제공합니다. 속성은 필드의 값을 읽거나 설정하는 데 사용됩니다.

예제: 속성 정의 및 사용 (Defining and Using Properties)

using System;

namespace PropertyExample
{
    class Person
    {
        // 자동 구현 속성 (Auto-Implemented Properties)
        public string Name { get; set; }
        public int Age { get; set; }

        // 계산된 속성 (Calculated Property)
        public bool IsAdult
        {
            get { return Age >= 18; }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Person person = new Person();
            person.Name = "Alice";
            person.Age = 30;

            Console.WriteLine("Name: " + person.Name);
            Console.WriteLine("Age: " + person.Age);
            Console.WriteLine("Is Adult: " + person.IsAdult);
        }
    }
}

이 예제에서 Person 클래스는 NameAge 속성을 가지며, IsAdult 계산된 속성을 통해 성인 여부를 판단합니다. Program 클래스에서 Person 객체를 생성하고 속성을 설정한 후 값을 출력합니다.

정적 메서드와 변수 (Static Methods and Variables)

정적 메서드와 변수는 클래스 자체에 속하며, 객체 인스턴스 없이 클래스 이름으로 접근할 수 있습니다.

예제: 정적 메서드와 변수 (Static Methods and Variables)

using System;

namespace StaticExample
{
    class MathUtilities
    {
        public static double PI = 3.14159;

        public static double CalculateCircleArea(double radius)
        {
            return PI * radius * radius;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            double radius = 5;
            double area = MathUtilities.CalculateCircleArea(radius); // 정적 메서드 호출 (Calling a Static Method)
            Console.WriteLine("Area of the circle: " + area);
        }
    }
}

이 예제에서 MathUtilities 클래스는 정적 변수 PI와 정적 메서드 CalculateCircleArea를 정의합니다. Program 클래스에서 객체를 생성하지 않고 MathUtilities 클래스를 통해 정적 메서드를 호출합니다.

메서드 및 속성 종합 예제 (Comprehensive Example of Methods and Properties)

using System;

namespace ComprehensiveExample
{
    class Car
    {
        // 속성 (Properties)
        public string Make { get; set; }
        public string Model { get; set; }
        public int Year { get; set; }
        private int speed;

        // 속성 (Property) with custom getter and setter
        public int Speed
        {
            get { return speed; }
            set
            {
                if (value < 0)
                {
                    speed = 0;
                }
                else
                {
                    speed = value;
                }
            }
        }

        // 메서드 (Method)
        public void Accelerate(int increment)
        {
            Speed += increment;
        }

        public void Decelerate(int decrement)
        {
            Speed -= decrement;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Car myCar = new Car();
            myCar.Make = "Toyota";
            myCar.Model = "Corolla";
            myCar.Year = 2020;
            myCar.Speed = 50;

            Console.WriteLine($"Make: {myCar.Make}");
            Console.WriteLine($"Model: {myCar.Model}");
            Console.WriteLine($"Year: {myCar.Year}");
            Console.WriteLine($"Speed: {myCar.Speed} km/h");

            myCar.Accelerate(20);
            Console.WriteLine($"Speed after accelerating: {myCar.Speed} km/h");

            myCar.Decelerate(30);
            Console.WriteLine($"Speed after decelerating: {myCar.Speed} km/h");
        }
    }
}

이 종합 예제에서는 Car 클래스가 여러 속성과 메서드를 가지고 있으며, 이를 통해 차량의 상태를 관리하고 속도를 조절할 수 있습니다. Program 클래스에서 Car 객체를 생성하고 다양한 속성 설정 및 메서드 호출을 통해 차량의 상태를 출력합니다.

이렇게 메서드와 속성을 사용하여 클래스의 데이터와 동작을 정의하고 관리할 수 있습니다. C#의 강력한 객체 지향 기능을 통해 코드의 재사용성과 가독성을 높일 수 있습니다.


Posted in C#

Leave a Reply

Your email address will not be published. Required fields are marked *