아카이빙/C#

[C#] Delegate (대리자)

셩님 2018. 6. 25. 15:37

[C#] Delegate (대리자)

Delegate란?

  • 특정 매개변수들이나 반환형식이 있는 메소드에 대한 참조를 나타내는 형식 (C/C++의 함수 포인터)

  • Delegate를 인스턴스화하면 모든 메소드가 있는 인스턴스를 호환되는 반환형식에 연결할 수 있으며, Delegate의 인스턴스를 통해 메소드를 호출 할 수 있다.

  • 메소드를 다른 메소드에 인수로 전달하는 데에 사용된다.

  • 콜백 메소드를 정의할 수 있다.

사용 예

class MainApp
{
   //string을 인수로 받고, void를 반환하는 delegate 선언
   public delegate void Del(string message);

   public static void DelegateMethod(string message)
  {
       Console.WriteLine("DelegateMethod : {0}", message);
  }

   static void Main()
  {
       // delegate 인스턴스화
       Del handler = DelegateMethod;
       
       // delegate 호출
       handler("Hello, World!");
  }
}

메소드를 매개변수로 전달

public void MethodWithCallback(int param1, int param2, Del callback)
{
   callback("The number is: " + (param1 + param2).ToString());
}

MethodWithCallback(10, 20, handler);
  • 콘솔에 The number is: 30이라고 출력

인스턴스의 메소드를 참조

  • 다음과 같은 클래스를 정의

class MethodClass
{
   public void Method1(string message){
       Console.WriteLine("Method1 : {0}", message);
  }
   public void Method2(string message){
       Console.WriteLine("Method2 : {0}", message);
  }
}
  • 예시

MethodClass obj = new MethodClass();
Del d1 = obj.Method1;
Del d2 = obj.Method2;
Del d3 = DelegateMethod;

Del allMethodsDelegate = d1 + d2;
allMethodsDelegate += d3;

allMethodsDelegate("d1 d2 d3");
/* result
Method1 : d1 d2 d3
Method2 : d1 d2 d3
DelegateMethod : d1 d2 d3
*/

allMethodsDelegate -= d1;
allMethodsDelegate("d2 d3");
/* result
Method2 : d2 d3
DelegateMethod : d2 d3
*/

Delegate의 복사

  • 다음과 같이 delegate를 복사할 수도 있다.

Del oneMethodDelegate = allMethodsDelegate - d2;
oneMethodDelegate("d3");
/* result
DelegateMethod : d3
*/

InvocationList

  • delegate에 등록된 메소드를 참조할 수 있다.

//length
Console.WriteLine(allMethodsDelegate.GetInvocationList().Length);

//Reference to elements.
Del inv1 = allMethodsDelegate.GetInvocationList()[0] as Del;
Del inv2 = allMethodsDelegate.GetInvocationList()[1] as Del;
inv1("d1");
inv2("d2");

/* result
Method2 : d1
DelegateMethod : d2
*/

참조


'아카이빙 > C#' 카테고리의 다른 글

[C#] Delegate와 익명메소드  (0) 2018.06.25
[C#] Delegate는 언제 사용하는가  (0) 2018.06.25
[C#] 예외처리  (0) 2018.06.21
[C#] 제네릭의 형식 제약  (0) 2018.06.21
[C#] 제네릭 클래스  (0) 2018.06.21