๋ธ๋ฆฌ๊ฒ์ดํธ ์ฒด์ธ(delegate chain)
: ๋ธ๋ฆฌ๊ฒ์ดํธ ํ๋๊ฐ ์ฌ๋ฌ๊ฐ์ ๋ฉ์๋๋ฅผ ๋์์ ์ฐธ์กฐํ๋ ๊ฒ.
์ฌ์ฉ ์์ ์ฝ๋
using System.Collections;
namespace DelegateEx
{
delegate void CalDelegate(int x , int y);
class Program
{
static void Add(int x, int y)
{
Console.WriteLine(x + y);
}
static void Sub(int x, int y)
{
Console.WriteLine(x - y);
}
static void Mul(int x, int y)
{
Console.WriteLine(x * y);
}
static void Div(int x, int y)
{
Console.WriteLine(x / y);
}
static void Main(string[] args)
{
CalDelegate cd = Add;
// ์ฒซ๋ฒ์งธ ๋ฐฉ๋ฒ `+=` ํน์ `-=` ์ฌ์ฉ
cd += Sub;
cd += Mul;
cd += Div;
cd(10, 5);
Console.WriteLine("Multiply๋ฅผ ์ฒด์ด๋์์ ์ ๊ฑฐ");
cd -= Mul;
cd(10, 5);
CalDelegate cd2 = new CalDelegate(Add)
// ๋๋ฒ์งธ ๋ฐฉ๋ฒ + new ์ฐ์ฐ์๋ก ๊ฐ์ฒด์์ฑ ๋ฐ `+` ์ฐ์ฐ์ฌ์ฉ.
+ Sub
+ Mul
+ Div;
// ์ด๋ ๊ฒ ์ฒด์ด๋์ ํด์ค๋ ๋๋ค.
cd(10, 5);
CalDelegate cd3 = (CalDelegate)Delegate.Combine(
// ์ธ๋ฒ์งธ ๋ฐฉ๋ฒ Combine ํจ์ ์ฌ์ฉ๊ณผ CalDelegate๋ก ํ๋ณํ
new CalDelegate(Add),
new CalDelegate(Sub),
new CalDelegate(Mul),
new CalDelegate(Div)
);
cd(10, 5);
}
}
}
15
5
50
2
Multiply๋ฅผ ์ฒด์ด๋์์ ์ ๊ฑฐ
15
5
2
15
5
2
15
5
2
- ์ด ์ธ๊ฐ์ง ๋ฐฉ๋ฒ์ ์ด์ฉํด์
๋ธ๋ฆฌ๊ฒ์ดํธ ์ฒด์ธ
์ ๊ตฌํํ๋ค.
์ฒซ๋ฒ์งธ ๋ฐฉ๋ฒ
+=
ํน์-=
์ฌ์ฉCalDelegate cd = Add; // ์ฒซ๋ฒ์งธ ๋ฐฉ๋ฒ `+=` ํน์ `-=` ์ฌ์ฉ cd += Sub; cd += Mul; cd += Div; cd(10, 5); Console.WriteLine("Multiply๋ฅผ ์ฒด์ด๋์์ ์ ๊ฑฐ"); cd -= Mul; cd(10, 5);
๋๋ฒ์งธ ๋ฐฉ๋ฒ
new
์ฐ์ฐ์๋ก ๊ฐ์ฒด์์ฑ ๋ฐ+
์ฐ์ฐ์ฌ์ฉ.CalDelegate cd2 = new CalDelegate(Add) + Sub + Mul + Div; cd(10, 5);
์ธ๋ฒ์งธ ๋ฐฉ๋ฒ
Combine
ํจ์ ์ฌ์ฉ๊ณผCalDelegate
๋ก ํ๋ณํCalDelegate cd3 = (CalDelegate)Delegate.Combine( // ์ธ๋ฒ์งธ ๋ฐฉ๋ฒ Combine ํจ์ ์ฌ์ฉ๊ณผ CalDelegate๋ก ํ๋ณํ new CalDelegate(Add), new CalDelegate(Sub), new CalDelegate(Mul), new CalDelegate(Div) ); cd(10, 5);
'๐ป Programming Language > C#' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
37. ๋ธ๋ฆฌ๊ฒ์ดํธ๋ฅผ ํตํ ์ด๋ฒคํธ ์ฒ๋ฆฌ (0) | 2022.04.08 |
---|---|
36. ์ต๋ช ๋ฉ์๋ (0) | 2022.04.08 |
34. ์ ๋ค๋ฆญ ๋ธ๋ฆฌ๊ฒ์ดํธ(Generic Delegate) & ์ฝ๋ฐฑํจ์ (0) | 2022.04.08 |
33. ๋ธ๋ฆฌ๊ฒ์ดํธ(delegate) ์ฌ์ฉ (0) | 2022.04.08 |
32. ๋ธ๋ฆฌ๊ฒ์ดํธ(delegate)์ ๊ธฐ๋ณธ ๊ฐ๋ (0) | 2022.04.08 |