일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | 7 |
8 | 9 | 10 | 11 | 12 | 13 | 14 |
15 | 16 | 17 | 18 | 19 | 20 | 21 |
22 | 23 | 24 | 25 | 26 | 27 | 28 |
29 | 30 |
Tags
- JS
- 문자열 파싱
- 코딩테스트
- programmers
- DP
- 이진탐색
- Algorithm
- 그래프 탐색
- BAEKJOON
- 자료구조
- 알고리즘
- 파이썬
- 삼성sw역테
- JavaScript
- 자바스크립트
- sort
- 카카오
- 동적 프로그래밍
- c#
- 코드트리
- DART
- 백준
- BFS
- 못그리지만
- 스터디
- 구현
- 프로그래머스
- Flutter
- Java
- 쓰셨잖아
Archives
- Today
- Total
Algo 쓰자
35. 델리게이트 체인(delegate chain) 본문
델리게이트 체인(delegate chain)
: 델리게이트 하나가 여러개의 메소드를 동시에 참조하는 것.
사용 예제 코드
using System.Collections;
namespace DelegateEx
{
delegate void CalDelegate(int x , int y);
class Program
{
static void Add(int x, int y)
{
Console.WriteLine(x + y);
}
static void Sub(int x, int y)
{
Console.WriteLine(x - y);
}
static void Mul(int x, int y)
{
Console.WriteLine(x * y);
}
static void Div(int x, int y)
{
Console.WriteLine(x / y);
}
static void Main(string[] args)
{
CalDelegate cd = Add;
// 첫번째 방법 `+=` 혹은 `-=` 사용
cd += Sub;
cd += Mul;
cd += Div;
cd(10, 5);
Console.WriteLine("Multiply를 체이닝에서 제거");
cd -= Mul;
cd(10, 5);
CalDelegate cd2 = new CalDelegate(Add)
// 두번째 방법 + new 연산자로 객체생성 및 `+` 연산사용.
+ Sub
+ Mul
+ Div;
// 이렇게 체이닝을 해줘도 된다.
cd(10, 5);
CalDelegate cd3 = (CalDelegate)Delegate.Combine(
// 세번째 방법 Combine 함수 사용과 CalDelegate로 형변환
new CalDelegate(Add),
new CalDelegate(Sub),
new CalDelegate(Mul),
new CalDelegate(Div)
);
cd(10, 5);
}
}
}
15
5
50
2
Multiply를 체이닝에서 제거
15
5
2
15
5
2
15
5
2
- 총 세가지 방법을 이용해서
델리게이트 체인
을 구현했다.
첫번째 방법
+=
혹은-=
사용CalDelegate cd = Add; // 첫번째 방법 `+=` 혹은 `-=` 사용 cd += Sub; cd += Mul; cd += Div; cd(10, 5); Console.WriteLine("Multiply를 체이닝에서 제거"); cd -= Mul; cd(10, 5);
두번째 방법
new
연산자로 객체생성 및+
연산사용.CalDelegate cd2 = new CalDelegate(Add) + Sub + Mul + Div; cd(10, 5);
세번째 방법
Combine
함수 사용과CalDelegate
로 형변환CalDelegate cd3 = (CalDelegate)Delegate.Combine( // 세번째 방법 Combine 함수 사용과 CalDelegate로 형변환 new CalDelegate(Add), new CalDelegate(Sub), new CalDelegate(Mul), new CalDelegate(Div) ); cd(10, 5);
'💻 Programming Language > C#' 카테고리의 다른 글
37. 델리게이트를 통한 이벤트 처리 (0) | 2022.04.08 |
---|---|
36. 익명메소드 (0) | 2022.04.08 |
34. 제네릭 델리게이트(Generic Delegate) & 콜백함수 (0) | 2022.04.08 |
33. 델리게이트(delegate) 사용 (0) | 2022.04.08 |
32. 델리게이트(delegate)의 기본 개념 (0) | 2022.04.08 |