중첩 클래스, 분할 클래스, 확장 메서드

Fruit·2023년 3월 29일

✨ Hello C#!

목록 보기
30/34
post-thumbnail

🌸 중첩 클래스

  • 클래스 안에 선언되어 있는 클래스이다.
  • 상위 클래스의 멤버에 접근할 수 있다.
using System;

namespace NestedClass
{
    class Container
    {
        public class Nested     // 중첩 클래스
        {
            private Container parent;

            public Nested()
            {
            }
            public Nested(Container parent)
            {
                this.parent = parent;
            }
        }
    }

    class MainApp
    {
        static void Main(string[] args)
        {
            Container.Nested nest = new Container.Nested();
        }
    }
}



🌸 분할 클래스: partial

  • 여러 번 나눠서 구현하는 클래스이다.
  • 소스 코드 관리의 편의를 제공한다.

parital 클래스 {}

using System;

namespace PartialClass
{
    partial class MyClass
    {
        public void Metod1()
        {
            Console.WriteLine("Method1");
        }

        public void Metod2()
        {
            Console.WriteLine("Method2");
        }
    }

    partial class MyClass
    {
        public void Metod3()
        {
            Console.WriteLine("Method3");
        }
    }

    class MainApp
    {
        static void Main(string[] args)
        {
            MyClass obj = new MyClass();
            obj.Metod1();
            obj.Metod2();
            obj.Metod3();
        }
    }
}

[실행 결과]
Method1
Method2
Method3



🌸 확장 메서드

  • 기존 클래스의 기능을 확장한다.

static 클래스 이름 {
  static 메서드 이름 (this 대상 형식 식별자, ...) {} }


예제 2

using MyExtension;
using System;

namespace MyExtension
{
    public static class IntegerExtension		// static 수식
    {
        public static int Power(this int myInt, int exponent)		// static 수식, this 키워드
        {
            int result = myInt;

            for (int i = 1; i < exponent; i++)
                result = result * myInt;

            return result;
        }
    }
}

namespace ExtensionMethod
{
    class MainApp
    {
        static void Main(string[] args)
        {
            Console.WriteLine($"3^4: {3.Power(4)}");
            Console.WriteLine($"2^10: {2.Power(10)}");
        }
    }
}

[실행 결과]
3^4: 81
2^10: 1024

예제 1

using MyExtension;

namespace MyExtension
{
    public static class StringExtension
    {
        public static string Append(this string myStr, string input)
        {
            string result = myStr + input;
            
            return result;
        }
    }
}

namespace ExtensionMethod
{
    class MainApp
    {
        static void Main(string[] args)
        {
            string hello = "Hello";

            Console.WriteLine(hello.Append(" Fruit!"));
        }
    }
}

[실행 결과]
Hello Fruit!

▪ 참고: Hello Fruit! - 클래스

profile
🌼인생 참 🌻꽃🌻 같다🌼

0개의 댓글