์ต๋ช
๋ฉ์๋(Anonymous Method)
: ์ด๋ฆ์ด ์๋ ๋ฉ์๋
์ ์ธํ์
๋ธ๋ฆฌ๊ฒ์ดํธ ์ธ์คํด์ค๋ช
= delegate(๋งค๊ฐ๋ณ์)
{
์คํ์ฝ๋ ...
}
์ฌ์ฉ ์์ ์ฝ๋
using System.Collections;
namespace AnonymousMethodEx
{
delegate int CalDelegate(int x, int y);
class Program
{
static void Main(string[] args)
{
CalDelegate cd;
cd = delegate (int x, int y)
{
return x * y;
};
Console.WriteLine($"{cd(10, 20)}");
}
}
}
Output
200
delegate
๋ ์ธ์คํด์ค๋ฅผ ๋ง๋ค ์ ์๋ ํด๋์ค์ฒ๋ผ ๋์
์ ํ๊ธฐ ๋๋ฌธ์ ํด๋์ค ๋ฐ์ผ๋ก ๋นผ์ ์์ฑํ๋๊ฒ ์ผ๋ฐ์ ์ด์ง๋ง ์ํฉ์ ๋ฐ๋ผ์ ํด๋์ค ๋ด๋ถ์ ์์ฑํ๋ ๊ฒฝ์ฐ๋ ์กด์ฌํ๋ค.
์ต๋ช
๋ฉ์๋์ ํ์ฉ(feat. Bubble Sort)
using System.Collections;
namespace AnonymousMethodEx
{
delegate int SelectSort(int x, int y);
class Program
{
static void BSort(int[] arr, SelectSort ss)
{
int temp = 0;
for (int i = 0; i < arr.Length - 1; i++)
{
for (int j = 0; j < arr.Length - (i+1); j++)
{
if (ss(arr[j],arr[j+1]) > 0)
{
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
}
static void Main(string[] args)
{
int[] array = { 2, 4, 1, 10, 7 };
SelectSort ascend;
ascend = delegate(int x, int y){
if (x > y) return 1;
else if (x == y) return 0;
else return -1;
};
BSort(array, ascend);
Console.WriteLine("์ค๋ฆ์ฐจ์ : ");
foreach (int x in array)
{
Console.Write($"{x} ");
}
Console.WriteLine();
SelectSort descend;
descend = delegate (int x, int y) {
if (x < y) return 1;
else if (x == y) return 0;
else return -1;
};
BSort(array, descend);
Console.WriteLine("๋ด๋ฆผ์ฐจ์ : ");
foreach (int x in array)
{
Console.Write($"{x} ");
}
Console.WriteLine();
int[] array2 = { 3, 2, 4, 1, 10, 7, 21, 42, 5, 13 };
BSort(array2, delegate(int x, int y)
{
if (x > y) return 1;
else if (x == y) return 0;
else return -1;
});
Console.WriteLine("๋ฉ์๋์ ์ธ์์์ ์ ์ธํ ์ต๋ช
๋ฉ์๋ ์ค๋ฆ์ฐจ์ : ");
foreach (int x in array2)
{
Console.Write($"{x} ");
}
Console.WriteLine();
}
}
}
Output
์ค๋ฆ์ฐจ์ :
1 2 4 7 10
๋ด๋ฆผ์ฐจ์ :
10 7 4 2 1
๋ฉ์๋์ ์ธ์์์ ์ ์ธํ ์ต๋ช
๋ฉ์๋ ์ค๋ฆ์ฐจ์ :
1 2 3 4 5 7 10 13 21 42
์ต๋ช
ํจ์
๋ ๋ค์ํ๊ฒ ํ์ฉ๋ ์ ์๋ค. ์์ ์ฝ๋์์๋ ์ธ์คํด์ค๋ฅผ ์์ฑํ ๋ ์ต๋ช
ํจ์๋ฅผ ์์ฑํ๋ ๋ฐฉ์
๊ณผ ๋ฉ์๋์ ์ธ์๋ก ๋๊ธธ๋ ์ต๋ช
ํจ์๋ฅผ ํตํด ๋ฐ๋ก ์์ฑํ๋ ๋ฐฉ์
๋ ๊ฐ์ง๋ฅผ ์ค์ตํ์๋ค.
SelectSort ascend;
ascend = delegate(int x, int y){
if (x > y) return 1;
else if (x == y) return 0;
else return -1;
};
BSort(array, ascend);
Console.WriteLine("์ค๋ฆ์ฐจ์ : ");
foreach (int x in array)
{
Console.Write($"{x} ");
}
Console.WriteLine();
- ์ฒซ๋ฒ์งธ ๋ฐฐ์ด์ ๋ํ์ฌ ์ค๋ฆ์ฐจ์๊ณผ ๋ด๋ฆผ์ฐจ์ ๋ฐฉ์์ด ๋๊ฐ์ ํ๋๋ง ํ์ธํด๋ณด์
- ๋จผ์
SelectSort
์ ๋ํ ์ธ์คํด์ค๋ก ascend
์ธ์คํด์ค๋ฅผ ์์ฑํ ๋ค ์ต๋ช
ํจ์๋ฅผ ํตํด delegate
๋ก ๋ฉ์๋๋ฅผ ํ ๋นํ ๊ฒ์ ํ์ธํ ์ ์๋ค.
int[] array2 = { 3, 2, 4, 1, 10, 7, 21, 42, 5, 13 };
BSort(array2, delegate(int x, int y)
{
if (x > y) return 1;
else if (x == y) return 0;
else return -1;
});
Console.WriteLine("๋ฉ์๋์ ์ธ์์์ ์ ์ธํ ์ต๋ช
๋ฉ์๋ ์ค๋ฆ์ฐจ์ : ");
foreach (int x in array2)
{
Console.Write($"{x} ");
}
Console.WriteLine();
- ๋๋ฒ์งธ ๋ฐฐ์ด์ ์ ๋ ฌ์ ๋ํด์๋
BSort()
๋ฉ์๋๋ฅผ ํธ์ถํจ๊ณผ ๋์์ ์ธ์๋ก ์ต๋ช
ํจ์๋ฅผ ์ ์ธํด ์ค์ผ๋ก์จ ๋๊ฒจ์ฃผ์๋ค.
- ์์ ์ฝ๋๋ฅผ ํตํด ํ์ธํ ์ ์๋ค.