C# Delegate
2021. 1. 25. 17:44ㆍ개발 관련 학습정리/C#
반응형
Delegate란 대리자란 뜻으로 메서드를 참조하는 변수이다.
이러한 Delegate는 메서드를 대신 호출하여 실행시킬 수 있고 여러 메서드를 참조할수도 있다.
일반적인 Delegate
//////////////////////////////////////////////////////// Alert Class
class Class1
{
public delegate void Alert(string text);
public void notice(string text)
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("notice : " + text);
}
public void error(string text)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("error : " + text);
}
public void success(string text)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(text);
}
}
static void Main(string[] args)
{
Class1 class1 = new Class1();
Class1.Alert alertdelegate = new Class1.Alert(class1.notice);
alertdelegate("notice");
alertdelegate = new Class1.Alert(class1.error);
alertdelegate("error");
}
위의 Class1 클래스에서 메서드와 Delegate를 선언한 뒤, 메인에서 메서드 참조 후 호출한다.
alertdelegate는 처음에 notice 메서드를 참조하다 출력 뒤 error 메서드를 참조한다.
Callback Delegate
//////////////////////////////////////////////////////// Calculator Class
class Class1
{
public delegate int Cal(int a, int b);
public int add(int a, int b)
{
return a + b;
}
public int sub(int a, int b)
{
return a - b;
}
public int mul(int a, int b)
{
return a * b;
}
public void result(int a, int b, Cal cal)
{
Console.WriteLine(cal(a, b));
}
}
static void Main(string[] args)
{
Class1 class1 = new Class1();
Class1.Cal add = new Class1.Cal(class1.add);
Class1.Cal sub = new Class1.Cal(class1.sub);
class1.result(3, 5, add);
class1.result(7, 3, sub);
}
콜백 메서드를 이용하여 delegate를 인자로 보내고, 해당 인자에 따라 메서드를 호출한다.
이를 통해 한 메서드로 delegate를 이용하여 여러 하위 메서드를 호출할 수 있다.
Delegate chain
//////////////////////////////////////////////////////// Alert Class
class Class1
{
public delegate void Alert(string text);
public void notice(string text)
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("notice : " + text);
}
public void error(string text)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("error : " + text);
}
public void success(string text)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(text);
}
}
static void Main(string[] args)
{
Class1 class1 = new Class1();
Class1.Alert alert = new Class1.Alert(class1.notice);
alert += class1.error;
alert += class1.success;
alert("!!!");
alert -= class1.success;
alert("???");
}
Delegate는 여러개의 메서드를 참조할 수 있다.
+=, -=연산을 통해 메서드를 추가/삭제가 가능하며 이렇게 여러개를 연결시키는 것을 델리게이트 체인이라 한다.
반응형
'개발 관련 학습정리 > C#' 카테고리의 다른 글
C# Generic (0) | 2021.01.27 |
---|---|
C# 추상클래스와 인터페이스 (0) | 2021.01.26 |
c# property (0) | 2021.01.12 |
[C#] overriding 오버라이딩 / 메서드 숨기기 (hold) (1) | 2019.04.14 |
[C#] 클래스 : 정적필드, 얕은 복사와 깊은 복사, this 키워드 (0) | 2019.04.01 |