본문 바로가기
카테고리 없음

c# 델리게이트란

by 아뾰오옹 2021. 8. 11.
반응형

델리게이트란?

- 콜백프로그래밍에서 사용

- 델리게이트는 대리인/대리자 라는 의미를 가진 단어

- 델리게이트에 메소드의 주소를 할당한 후 델리게이트를 호출하면 이 델리게이트가 매소드를 호출해준다. 

 

델리게이트 선언

한정자 delegate 반환형식 델리게이트이름 (매개변수 목록);
delegate int Mydelegate(int a, int b);

 

델리게이트가 참조할 메소드 작성

int plus(int a, int b)
{
	return a + b;
    
}

int Minus(int a, int b)
{
	return a-b;
}

델리게이트가 메소드 참조

MyDelegate Callback;

Callback = new MyDelegate(Plus);
Console.WriteLine(Callback(3,4)); //7

Callback = new MyDelegate(Minus);
Console.WriteLine(Callback(3,4));//-1

 

델리게이트는 왜 사용할까?

델리게이트는 메소드에 참조이므로, 하나의 메소드에 매개변수를 델리게이트로 넘겨서 필요에 따라 델리게이트에서 다른 메소드를 참조하도록 할 수 있다.

 

 

delegate int Compare(int a, int b);


static int Asc(int a, int b){

....

}

static int Dsc(int a, int b){

....

}

static void BubbleSort(int[] DataSet, Compare Compare){

...

}

static void Main(string[] args){

	int[] array = {3,7,4,2,10};
    
    BubbleSort(array, new Compare(Asc) );
    
    BubbleSort(array, new Compare(Dsc) );
    
    

}

 

BubbleSort에서 델리게이트를 인자로 받을 때, 필요에 따라서 오름/내림 차순의 매소드를 호출할 수 있다. 

- 매소드를 인자로 넘겼다. 

 

 

 

반응형

댓글