Delegate
Delegate는 함수를 인스턴스화 해서 다른 함수로 넘겨줄 수가 있다.
즉, 다른 함수에서 delegate에 저장된 함수를 호출할 수 있다.
(제한자) delegate [반환형] 이름 (매개변수) public delegate void Del(string message); public static void DelegateMethod(string message) { Console.WriteLine(message); } Del handler = DelegateMethod; handler("Hello World");
delegate에 메서드를 등록하기 위해서는 반환형과 매개변수가 동일해야 한다.
Del d1 = obj.Method1; Del d2 = obj.Method2; Del d3 = obj.Method3; Del allMethodsDelegate = d1 + d2 + d3; Del allMethodsDelegate -= d1;
delegate는 둘 이상의 메서드를 등록할 수 있고, 등록된 메서드를 제거할 수도 있다.
반환형이 없는 기본 delegate
void Out(string coment) { Console.WriteLine(coment); } //Action<매개변수> Action변수명; Action<string> outAction = Out; outAction("치즈오믈렛"); //출력 : 치즈오믈렛
반환형이 있는 기본 delegate
int Sum(int a, int b) { return a + b; } //Func<매개변수n개,반환형> Func변수명 <>안에서 마지막에 들어오는 형식이 반환형이된다. Func<int,int,int> SumFunc = Sum; Console.WriteLine(SumFunc(1,2)); //출력 : 3
다른 함수에서 델리게이트에 접근할 때 추가, 삭제만 가능하게 만드는 키워드
delegate를 만들 때 일회성으로 사용할 함수를 만든다
//delegate(매개변수){실행문} Action<string> outAction = delegate(string coment){ Console.WriteLine(coment); }; outAction("치즈오믈렛") //출력 : 치즈오믈렛 Func<int,int,int> SumFunc = delegate (int a, int b){ return a + b;}; Console.WriteLine(SumFunc(1,2)); //출력 : 3
함수를 다른코드의 인수로 넘겨주어서 실행 가능한 코드
Delegate를 이용해서 비동기처리가 필요할 때 주로 사용한다
void Callback(Action<string> action) { action("반환"); } Callback(delegate (string s) { Console.WriteLine(s); }); //출력 : 반환
delegate를 생성할 때 익명메서드 보다 더 간단하게 생성
//(매개변수) => {실행문} Func<int,int,int> SumFunc = (a,b) => a + b; Console.WriteLine(SumFunc(1,2));