๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
๐Ÿ–ฅ๏ธ/C#

[C#] ๋ถ„ํ•  ํด๋ž˜์Šค, ํ™•์žฅ ๋ฉ”์„œ๋“œ

by HanaV 2023. 8. 17.
728x90

๋ถ„ํ•  ํด๋ž˜์Šค (partial)

ํ•˜๋‚˜์˜ ํด๋ž˜์Šค๋ฅผ ์•ž์— partial ํ‚ค์›Œ๋“œ๋ฅผ ๋ถ™์—ฌ์„œ ๋‚˜๋ˆ ์„œ ๊ด€๋ฆฌํ•˜๋Š” ๊ฒƒ์ด๋‹ค.

partial class MyClass
{
    public void MethodPart1()
    {
        Console.WriteLine("Method from Part 1");
    }
}
partial class MyClass
{
    public void MethodPart2()
    {
        Console.WriteLine("Method from Part 2");
    }
}
class Program
{
    static void Main()
    {
        MyClass myClass = new MyClass();
        myClass.MethodPart1(); // ์ถœ๋ ฅ: "Method from Part 1"
        myClass.MethodPart2(); // ์ถœ๋ ฅ: "Method from Part 2"
    }
}

 

ํ™•์žฅ ๋ฉ”์„œ๋“œ

์‚ฌ์šฉ์ž๊ฐ€ ์ •์˜ํ•œ ๋ฉ”์„œ๋“œ๋ฅผ ๋งˆ์น˜ ์›๋ž˜ ์žˆ๋Š” ๋ฉ”์„œ๋“œ์ฒ˜๋Ÿผ ์ƒ์„ฑ์ž ์—†์ด ๋ถˆ๋Ÿฌ์˜ค๊ฒŒ ํ•  ์ˆ˜๋„ ์žˆ๋Š”๋ฐ, ๋ฐ”๋กœ ํ™•์žฅ ๋ฉ”์„œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์ด๋‹ค. 

1. static์œผ๋กœ ์„ ์–ธํ•ด์•ผ ํ•œ๋‹ค.
2. ๊ฐ™์€ namespace์•ˆ์— ์žˆ๊ฑฐ๋‚˜, ๋‹ค๋ฅธ namespace์— ์žˆ์„ ๊ฒฝ์šฐ using์œผ๋กœ ๋ถˆ๋Ÿฌ์™€์ฃผ๋ฉด ๋œ๋‹ค.
3. ํ™•์žฅ ๋ฉ”์„œ๋“œ์˜ ๋งค๊ฐœ๋ณ€์ˆ˜์— this ํ‚ค์›Œ๋“œ๋ฅผ ๋ถ™์ธ๋‹ค.

using System;

namespace ExtensionMethodsExample
{
    public static class StringExtensions
    {
        public static string FirstLetterToUpper(this string input)
        {
            if (string.IsNullOrEmpty(input))
                return input;

            return char.ToUpper(input[0]) + input.Substring(1);
        }
    }

    class Program
    {
        static void Main()
        {
            string myString = "hello, world!";
            string capitalized = myString.FirstLetterToUpper();

            Console.WriteLine(capitalized); // "Hello, world!"
        }
    }
}

์œ„์˜ ์˜ˆ์ œ๋Š” ๊ฐ™์€ namspace์•ˆ์— ์žˆ์–ด์„œ ์‹คํ–‰์ด ์ž˜ ๋œ๋‹ค.

๋งŒ์•ฝ ๋‹ค๋ฅธ namespace์— ์žˆ์œผ๋ฉด

using System;
/*์ถ”๊ฐ€*/
using ExtensionMethodsExample;

namespace ExtensionMethodsExample
{
    public static class StringExtensions
    {
        public static string FirstLetterToUpper(this string input)
        {
            if (string.IsNullOrEmpty(input))
                return input;

            return char.ToUpper(input[0]) + input.Substring(1);
        }
    }
}

namespace OtherNamespace
{
    class Program
    {
        static void Main()
        {
            string myString = "hello, world!";
            string capitalized = myString.FirstLetterToUpper(); // ์—ฌ๊ธฐ์„œ ์˜ค๋ฅ˜ ๋ฐœ์ƒ

            Console.WriteLine(capitalized);
        }
    }
}

์ด๋ ‡๊ฒŒ using ExtensionMethodsExample;์„ ์จ์ค˜์•ผ ํ™•์žฅ ๋ฉ”์„œ๋“œ๋ฅผ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค.

 

 

728x90

"); wcs_do();