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
'๐ฅ๏ธ > C#' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
[์ด๊ฒ์ด C#์ด๋ค] Chapter07: ์ฐ์ต๋ฌธ์ (0) | 2023.08.17 |
---|---|
[C#] ๊น์๋ณต์ฌ ์์๋ณต์ฌ, readonly, ๊ตฌ์กฐ์ฒด, ํํ (0) | 2023.08.17 |
[C#] ์์, ๋คํ์ฑ, ์ค๋ฒ๋ผ์ด๋ฉ (0) | 2023.08.17 |
[์ด๊ฒ์ด C#์ด๋ค] Chapter06: ์ฐ์ต๋ฌธ์ (0) | 2023.08.16 |
[C#] ์ฐธ์กฐ ๋งค๊ฐ๋ณ์ ์ ๋ฌ, ์ฌ๋ฌ ๊ฐ์ ๊ฐreturn, ๊ฐ๋ณ ๊ฐ์์ ์ธ์, ์ ํ์ ์ธ์ (0) | 2023.08.16 |