C#에서는 메서드를 값으로 갖는 타입을 delegate 구문으로 제공한다.
1. 방법
int Clean (object arg);
→ delegate int FunDelegate(object arg);
= 예약어 반환값 타입명 (인자)
✍ 샘플 코드
internal class Program
{
delegate void DelegateCry();
delegate void DelegateSleep();
static void Main(string[] args)
{
Animal a = new Animal();
DelegateCry dc = new DelegateCry(a.Cry);
DelegateSleep ds = a.Sleep;
}
}
2. 실체
3. 메서드의 추가나 제거
internal class Program
{
delegate void DelegateCalculate(int x, int y);
static void Main(string[] args)
{
DelegateCalculate dc = Calculator.Add;
dc += Calculator.Substract;
dc += Calculator.Divide;
dc += Calculator.Multiply;
dc(10, 5);
dc -= Calculator.Divide;
dc(5, 0);
}
}
class Calculator
{
static public void Add(int x, int y) { Console.WriteLine(x + y); }
static public void Substract(int x, int y) { Console.WriteLine(x - y); }
static public void Divide(int x, int y) { Console.WriteLine(x / y); }
static public void Multiply(int x, int y) { Console.WriteLine(x * y); }
}
15
5
2
50
5
5
0
namespace Pjt
{
delegate void DelegateMethod();
internal class Caller
{
static void Main(string[] args)
{
DelegateMethod dm = CallBackMethod;
CalledClass c = new CalledClass();
c.Work(dm);
}
static void CallBackMethod()
{
Console.WriteLine("Called Backed");
}
}
class CalledClass
{
public void Work(DelegateMethod dm)
{
Console.WriteLine("Called Class Do Its Business...");
dm();
}
}
}
Called Class Do Its Business...
Called Backed
namespace Pjt
{
delegate void DelegateMethod();
internal class Caller
{
static void Main(string[] args)
{
DelegateMethod dm = CallBackClass.CallBackMethod;
CalledClass c = new CalledClass();
c.Work(dm);
}
static void CallBackMethod()
{
Console.WriteLine("Called Backed");
}
}
class CalledClass
{
public void Work(DelegateMethod dm)
{
Console.WriteLine("Called Class Do Its Business...");
dm();
}
}
class CallBackClass
{
public static void CallBackMethod()
{
Console.WriteLine("Called Back in Another Class");
}
}
}
Called Class Do Its Business...
Called Back in Another Class