C# 강좌 : 제 21강 - 델리게이트
델리게이트(Delegate)
델리게이트(Delegate)
란 메서드에 대한 참조
를 의미합니다.
델리게이트에 메서드의 주소를 할당한 후에 델리게이트를 호출하면 이 델리게이트가 메서드를 호출하게 됩니다.
델리게이트는 콜백 메서드 (CallBack Mehtod)
를 구현할 때 많이 사용합니다.
델리게이트가 호출할 때마다 원하는 메서드를 불러와 지정된 메서드를 실행할 수 있습니다.
델리게이트 구조
한정자 delegate 반환형식 델리게이트이름(매개변수목록);
델리게이트 선언
private delegate int MyDelegate(int a, int b);
MyDelegate
로 선언된 델리게이트에 매개변수 (int)
를 2개 받아 사용합니다.
int Plus(int a, int b)
{
return a + b;
}
int Minus(int a, int b)
{
return a - b;
}
Plus
와 Minus
메서드를 생성합니다. MyDelegate와 매개변수의 개수가 동일
해야 합니다.
private void Form1_Load(object sender, EventArgs e)
{
MyDelegate function;
function = new MyDelegate(Plus);
Console.WriteLine(function(3, 4));
function = new MyDelegate(Minus);
Console.WriteLine(function(7, 5));
}
위에서 선언된 MyDelegate를 function
으로 불러옵니다.
이 후, function
에 Plus
와 Minus
로 델리게이트가 참조할 메서드를 매개 변수로 넘깁니다.
function(a, b)
로 델리게이트를 호출합니다.
델리게이트 일반화(Delegate Generalization)
델리게이트 일반화 (Delegate Generalization)란 일반화(Generalization)
와 마찬가지로 데이터 형식(Data Type)을 연관성이 있는 2개 이상의 개체 집합을 묶어내는것
입니다.
다른 형식의 메서드도 일반화 하여 참조
할 수 있습니다.
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;
}
double Multiply(double a, double b)
{
return a * b;
}
double Division(double a, double b)
{
return a / b;
}
private void Form1_Load(object sender, EventArgs e)
{
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));
}
서로 다른 형식의 데이터 형식이라도 일반화를 통하여 델리게이트를 사용
할 수 있습니다.
델리게이트 체인(Delegate Chain)
델리게이트 체인(Delegate Chain)이란 여러 개의 메서드를 동시에 참조
하여 사용하는 방법입니다.
델리게이트를 호출할 때 델리게이트의 체인(+=, -=)에 따라 순서대로 호출
됩니다.
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번 : 인간
산술기호를 이용하여 델리게이트끼리 연결시켜 사용
할 수 있습니다. 어떤 순서로 연결하느냐에 따라 출력 순서가 달라집니다.
공유하기


댓글 남기기