ํ์ฅ ๋ฉ์๋๋ ๊ธฐ์กด ํด๋์ค์ ๊ธฐ๋ฅ์ ํ์ฅํ๋ ๊ธฐ๋ฒ์ด๋ค.
๊ธฐ๋ฐ ํด๋์ค๋ฅผ ๋ฌผ๋ ค๋ฐ์ ํ์ ํด๋์ค๋ฅผ ๋ง๋ ๋ค ์ฌ๊ธฐ์ ํ๋๋ ๋ฉ์๋๋ฅผ ์ถ๊ฐํ๋ ์์๊ณผ๋ ๋ค๋ฅด๋ค.
ํ์ฅ๋ฉ์๋๋ '๊ธฐ์กด ํด๋์ค'์ ๊ธฐ๋ฅ์ ํ์ฅํ๋ค.
ํ์ฅ ๋ฉ์๋๋ฅผ ์ด์ฉํ๋ฉด string ํด๋์ค์ ๋ฌธ์์ด์ ๋ค์ง๋ ๊ธฐ๋ฅ์ ๋ฃ์ ์๋ ์๊ณ ,
int ํ์์ ์ ๊ณฑ ์ฐ์ฐ ๊ธฐ๋ฅ์ ๋ฃ์ ์๋ ์๋ค.
<์์ >
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Console;
using MyExtension; //ํ์ฅ ๋ฉ์๋๋ฅผ ๋ด๋ ํด๋์ค์ ๋ค์์คํ์ด์ค๋ฅผ ์ฌ์ฉํ๋ค.
namespace MyExtension
{
public static class IntegerExtension
{
public static int Square(this int myInt)
{
return myInt * myInt;
}
public static int Power(this int myInt, int exponent)
{
int result = myInt;
for (int i = 1; i < exponent; i++)
result = result * myInt;
return result;
}
}
}
namespace ExtensionMethod
{
class MainApp
{
static void Main(string[] args)
{
WriteLine($"3^2 : {3.Square()}"); //3^2 : 9
WriteLine($"3^4 : {3.Power(4)}"); //3^4 : 81
WriteLine($"2^10 : {2.Power(10)}"); //2^10 : 1024
//๋ง์น Power()๊ฐ ์๋๋ถํฐ int ํ์์ ๋ฉ์๋์๋ ๊ฒ์ฒ๋ผ ์ฌ์ฉํ ์ ์๋ค.
}
}
}
<์์ 2>
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using static System.Console;
using MyExtension;
namespace MyExtension
{
public static class StringExtension
{
public static string Append(this string myString, string appendStr)
{
string thisStr = myString;
return thisStr += appendStr;
}
}
}
namespace ExtensionMethod
{
class MainApp
{
static void Main(string[] args)
{
string hello = "Hello";
WriteLine(hello.Append(", World!")); //Hello, World!
}
}
}
ํ์ฅ๋ฉ์๋๋ฅผ ์ ์ธํ๋ ๋ฐฉ๋ฒ์ ๋ค์๊ณผ ๊ฐ๋ค.
(1) ๋ฉ์๋๋ฅผ ์ ์ธํ๋, static ํ์ ์๋ก ์์ํด์ผ ํ๋ค.
(2) ๋ฉ์๋์ ์ฒซ๋ฒ์งธ ๋งค๊ฐ๋ณ์๋ ๋ฐ๋์ this ํค์๋์ ํจ๊ป ํ์ฅํ๊ณ ์ ํ๋ ํด๋์ค(ํ์)์ ์ธ์คํด์ค์ฌ์ผ ํ๋ค.
(3) (2)๋ค์ ๋ฐ๋ผ์ค๋ ๋งค๊ฐ๋ณ์ ๋ชฉ๋ก์ด ์ค์ ๋ก ํ์ฅ ๋ฉ์๋๋ฅผ ํธ์ถํ ๋ ์ ๋ ฅ๋๋ ๋งค๊ฐ๋ณ์์ด๋ค.
(๋ฉ์๋๋ ํด๋์ค ์์ด ์ ์ธ๋ ์ ์์ผ๋ฏ๋ก ํด๋์ค๋ฅผ ํ๋ ์ ์ธํ๊ณ , ๊ทธ ์์ ํ์ฅ ๋ฉ์๋๋ฅผ ์ ์ธํ๋ค.
์ด๋ ์ ์ธํ๋ ํด๋์ค๋ ์ญ์ static ํ์ ์๋ก ์์ํด์ผ ํ๋ค.)
namespace ๋ค์์คํ์ด์ค์ด๋ฆ
{
public static class ํด๋์ค์ด๋ฆ
{ //๋์ํ์: ํ์ฅํ๊ณ ์ ํ๋ ํด๋์ค ๋๋ ํ์
public static ๋ฐํ_ํ์ ๋ฉ์๋์ด๋ฆ(this ๋์ํ์ ์๋ณ์, ๋งค๊ฐ๋ณ์๋ชฉ๋ก)
{
//
}
}
}
public static int Power(this int myInt, int exponent)
{
int result = myInt;
for (int i = 1; i < exponent; i++)
result = result * myInt;
return result;
}
'C# > ์ด๊ฒ์ด C#์ด๋ค' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
32. ํํ (0) | 2022.02.14 |
---|---|
31. ๊ตฌ์กฐ์ฒด, ๋ณ๊ฒฝ ๋ถ๊ฐ๋ฅ ๊ตฌ์กฐ์ฒด(readonly struct) (0) | 2022.02.14 |
29. ๋ถํ ํด๋์ค (0) | 2022.02.11 |
28. ์ค์ฒฉ ํด๋์ค (0) | 2022.02.11 |
27. ์ฝ๊ธฐ ์ ์ฉ ํ๋, readonly (0) | 2022.02.11 |