접근제한자 delegate 대상_메서드_반환타입 식별자(… … 대상_메서드_매개변수_목록 … …);
예제 1
namespace Cshop_v6._0
{
public class Mathematics
{
delegate int CalcDelegate(int x, int y);
static int Add(int x, int y) { return x + y; }
static int Subtract(int x, int y) { return x - y; }
static int Multiply(int x, int y) { return x * y; }
static int Devide(int x, int y) { return x / y; }
CalcDelegate[] methods;
public Mathematics()
{
methods = new CalcDelegate[] { Mathematics.Add, Mathematics.Subtract, Mathematics.Multiply, Mathematics.Devide };
}
public void Calculate(char opCode, int operand1, int operand2)
{
switch (opCode)
{
case '+': Console.WriteLine("+: " + methods[0](operand1, operand2)); break;
case '-': Console.WriteLine("-: " + methods[1](operand1, operand2)); break;
case '*': Console.WriteLine("*: " + methods[2](operand1, operand2)); break;
case '/': Console.WriteLine("/: " + methods[3](operand1, operand2)); break;
}
}
}
class Program
{
delegate void WorkDelegate(char arg1, int arg2, int arg3);
static void Main()
{
Mathematics math = new Mathematics();
WorkDelegate work = math.Calculate;
work('+', 10, 5);
work('-', 10, 5);
work('*', 10, 5);
work('/', 10, 5);
}
}
}
예제 2
namespace Cshop_v6._0
{
class Program
{
delegate void CalcDelegate(int x, int y);
static void Add(int x, int y) { Console.WriteLine(x + y); }
static void Subtract(int x, int y) { Console.WriteLine(x - y); }
static void Multiply(int x, int y) { Console.WriteLine(x * y); }
static void Divide(int x, int y) { Console.WriteLine(x / y); }
static void Main()
{
CalcDelegate calc = Add;
calc += Subtract;
calc += Multiply;
calc += Divide;
calc(10, 5);
// 출력결과
/*
15
5
50
2
*/
Console.WriteLine("=================================================================");
calc -= Divide;
calc(10, 5);
// 출력결과
/*
15
5
50
*/
}
}
}