Notice
Recent Posts
Recent Comments
Link
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
Archives
Today
Total
07-05 07:53
관리 메뉴

nomad-programmer

[Programming/C#] 확장 메소드 본문

Programming/C#

[Programming/C#] 확장 메소드

scii 2020. 9. 9. 18:19

확장 메소드(Extension Method)는 기존 클래스의 기능을 확장하는 기법이다. 부모 클래스를 물려받아 파생 클래스를 만든 뒤 여기에 필드나 메소드를 추가하는 상속과는 다르다.

확장 메소드는 이미 존재하는 클래스의 기능을 확장한다.

확장 메소드를 이용하면 string 클래스에 문자열을 뒤집는 기능을 넣을 수도 있고, int 형식에 제곱 연산 기능을 넣을 수도 있다.

확장 메소드를 선언하는 방법

메소드를 선언하되, static 한정자로 수식해야 한다. 그리고 이 메소드의 첫 번째 매개 변수는 반드시 this 키워드와 함께 확장하고자 하는 클래스(형식)의 인스턴스여야 한다. 그 뒤에 따라오는 매개 변수 목록이 실제로 확장 메소드를 호출할 때 입력되는 매개 변수이다.
메소드는 클래스 없이 선언될 수 없기 때문에 클래스를 하나 선언해야하며 선언하는 클래스 역시도 static 한정자로 수식해야 한다.

using System;

namespace CSharpExample
{
    public static class IntegerExtension
    {
        public static int Square(this int myInt)
        {
            return myInt * myInt;
        }

        public static int Power(this int myInt, int exponent)
        {
            int res = myInt;
            for(int i=1; i<exponent; i++)
            {
                res *= myInt;
            }
            return res;
        }
    }

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

            return 0;
        }
    }
}


/* 결과 

3^2 : 9
3^4 : 81
2^10 : 1024

*/

 

string 확장

using System;

namespace CSharpExample
{
    public static class StringExtension
    {
        // 문자열 뒤집는 확장 메소드
        public static string ReverseStr(this string myStr)
        {
            char[] charLst = myStr.ToCharArray();
            for (int i = 0; i < (charLst.Length / 2); i++)
            {
                char tmp = charLst[i];
                charLst[i] = charLst[charLst.Length - 1 - i];
                charLst[charLst.Length - 1 - i] = tmp;
            }
            return new string(charLst);
        }

        // 문자열 append
        public static string AppendStr(this string myStr, string addStr)
        {
            return myStr + addStr;
        }
    }

    class MainApp
    {
        static int Main(string[] args)
        {
            Console.WriteLine("Hello".ReverseStr());
            Console.WriteLine("Hello".AppendStr(" World!"));

            return 0;
        }
    }
}


/* 결과

olleH
Hello World!

*/
Comments