30. νμ₯ λ©μλ
νμ₯ λ©μλλ κΈ°μ‘΄ ν΄λμ€μ κΈ°λ₯μ νμ₯νλ κΈ°λ²μ΄λ€.
κΈ°λ° ν΄λμ€λ₯Ό λ¬Όλ €λ°μ νμ ν΄λμ€λ₯Ό λ§λ λ€ μ¬κΈ°μ νλλ λ©μλλ₯Ό μΆκ°νλ μμκ³Όλ λ€λ₯΄λ€.
νμ₯λ©μλλ 'κΈ°μ‘΄ ν΄λμ€'μ κΈ°λ₯μ νμ₯νλ€.
νμ₯ λ©μλλ₯Ό μ΄μ©νλ©΄ 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;
}