번역: 대표, 파견
콜백 메서드를 구현할때 많이 사용됨.
한정자 delegate 반환형식 델리케이트이름(메개변수목록);
델리게이트 선언
private delgate int MyDeligate(intt a, int b)
int Plus(int a, int b)
{
return a + b;
}
int Minus(int a, int b)
{
return a - b;
}
private void Form1_Load(object sender, EventArgs e)
{
MyDelegate function;
function = new MyDeligate(Plus);
Console.WriteLine(function(3,4));
function = nwe MyDeligate(Minus);
Console.WriteLine(function(7,5));
}
델리게이트와 제너럴을 함께 사용하여 코드의 자유도를 높일 수 있다.
private delegate T MyDelegate<T>(T a, T b);
int Plus(int a, int b)
{
return a+b;
}
int Minus(int a, int b)
{
return a-b;
}
int Multiply(int a, int b)
{
return a*b;
}
int Division(int a, int b)
{
return a/b;
}
private void Form1_Load(object sender, EveentArgs)
{
MyDelegate<int> function1 = new MyDelegate<int>(Plus);
Console.WriteLine(function1(3, 4));
MyDelegate<int> function2 = new MyDelegate<int>(Minus);
Console.WriteLine(function2(3, 4));
MyDelegate<double> function3 = new MyDelegate<double>(Multiply);
Console.WriteLine(function3(3, 4));
MyDelegate<double> function4 = new MyDelegate<double>(Division);
Console.WriteLine(function4(3, 4));
}
여러개의 메서드를 동시에 참조하여사용하는 것.
델리게이트를 호출할 때 델리게이트 체인(+=, -=)
에 따라 순서대로 호출됨
델리게이트끼리 연결시켜 사용
할 수 있음.private delegate void MyDelegate(string text);
void num_1 (string text)
{
Console.WriteLine("1번 : {0}", text);
}
void num_2(string text)
{
Console.WriteLine("2번 : {0}", text);
}
void num_3(string text)
{
Console.WriteLine("3번 : {0}", text);
}
private void Form1_Load(object sender, EventArgs e)
{
MyDelegate dele = new MyDelegate(num_1);
dele += new MyDelegate(num_2);
dele += new MyDelegate(num_3);
dele("사람");
dele -= new MyDelegate(num_2);
dele("인간");
}
// 1번 사람, 2번 사람, 3번 사람
// 1번 인간, 3번 인간