순서

I. Delegate

II. Delegate Example (세부사항)

1. 기본구현 Example
2. Func/Action 사용 Example
3. Parameter Example
4. Chain, Multicasting Example

 


I. Delegate

 

1. Delegate는 메소드를 쳐다보고 호출하는 역할을 한다.

2. 어떤 함수를 실행시킬 코드를 런타임에 부여하는데

3. 네가 (Delegate가) 이 일을(Callback Function) 해줘 부여 가능하다.
     -> 이 일을 Callback method라고 한다.

4. Delegate를 통해 Method를 Parameter로 전달할 수 있어 Callback 구현에 용이하다.

5. Delegate에는 Method의 주소(Reference)가 할당된다.

6. 쓰레드와 이벤트에서 주로 사용된다.
    -> ex) Client / Server system에서 Client가 Server에 요청 시 Server의 Delegate 사용

7. Chain, Multicasting을 이용해 Delegate에 여러 Method들을 순차적으로 엮을 수 있다.

8. 한정자 delegate 리턴형 이름 (매개변수); 로 정의한다.
    -> delegate의 리턴형과 매개변수는 함수의 리턴형 매개변수와 동일해야만 한다.

 


II. Delegate Example

 

1. 기본구현 Example

using System;

namespace DeleApp {
  delegate int DeleIntInt(int i, int j); // 선언
  delegate void DeleVoid();
  
  public class CMain {
    static void Main() {
     // delegate 생성 및 메소드 할당
      DeleIntInt dii1 = new DeleIntInt(sum);
      DeleIntInt dii2 = new DeleIntInt(mul);
      
      int nSum = dii1(1,2);
      int nMul = dii2(2,4);
    }
    
    static int sum(int i, int j) => i+j;
    static int mul(int i, int j) => i*j;
    static void printHello() => Console.WriteLine("Hello");
  }
}

직접 delegate를 선언하는 방법을 보여준다.

 

2. Func / Action 사용 Example

직접 delegate를 선언하지 않고 만들 수 있다.

using System;

namespace DeleApp {

  public class CMain {
    static void Main() {
     // Func<in, in, ... , out>
     // Action<in, in, ...> 무조건 void 반환
     Func<int, int, int> funcDele1 = sum;
     Action<int, int> funcDele2 = sumPrint;
    }
    
    static int sum(int i, int j) => i+j;
    static void sumPrint(int i, int j) => Console.WriteLine($"{i+j}");
  }
}
Func : input parameter 쭉 넣고, 마지막엔 반환 type
Action : 무조건 void 반환 함수이며 input parameter만 넣음

굳이 직접 delegate 선언하지 않고 매개변수와 함수 type이 지정되어있다면
Func<inputType, inputType, .... , returnType>
Action<inputType, inputType, ... > -> 무조건 void return 함수만 가능
로 생성할 수 있다.

 

3. Parameter Example

주로 Delegate의 인자로 함수를 넘겨줄 수 있다.
또한 object를 인자로 받으면
내가 전달한 object에 대해 사용자가 원하는 일(Method)을 할 수 있다.

이 예제는 bubbleSort 예제로
내가 원하는 object를 원하는 method로 sort 하는 delegate 활용 예제이다

using System;

namespace DeleApp {
  // 2개의 object를 받고 bool을 반환하는 delegate
  delegate bool DeleSort(object obj1, object obj2);
  
  class CSorter {
  // 오브젝트 리스트, sort방법을 담은 함수를 Delegate에 전달함
    public static void bubbleSort(object[] obj, DeleSort deli) {
    
      for (int i=0; i<obj.Length; i++) {
        for (int j=0; j<i; j++) {
        // !!두 object를 전달받은 함수(delegate)로 비교한다.
        // object도, 함수(delegate)도 사용자 설정임
          if (dele(obj[i], obj[j])) {
            object temp = obj[j];
            obj[j] = obj[i];
            obj[i] = temp;
  }}}}}
  
  class CPersonAge {
    public CPersonAge(int _age) => age = _age;
    public int age { get; set; }
    
    public static bool sortAge(object o1, object o2) {
      return ((CPersonAge)o1).age >= ((CPersonAge)o2).age ? true : false;
  }}
  
  public class CMain {
    static void Main() {
      CPersonAge[] AgeList = new CPersonAge[3];
      AgeList[0] = new CPersonAge(10);
      AgeList[1] = new CPersonAge(16);
      AgeList[2] = new CPersonAge(26);
      
      // delegate에 함수 전달하여 생성.
      DeleSort myDeleSort = new Delesort(CPersonAge.sortAge);
      
      // 내 Obejct와 delegate에 전달한 sort Algorithm을 호출한다.
      CSorter.bubbleSort(AgeList, myDeleSort);
}}}

언제나 사용하고 싶은 Sort 알고리즘이 있는데
이 Sort 알고리즘은 객체(object)와 사용자 함수(delegate를 받는다)

사용자는 delegate에 내 사용자 함수를 인자로 전달하여 사용하면 된다.

 

4. Chain, Multicasting Example

delegate는 함수들을 Combine으로 연결하고 Remove로 제거할 수 있다(Chain)

이 연결을 간편하게 연산자 + - 로 구성할 수 있다.(Multicasting)
-> 
delegate는 Immutable 형식이다. (ex : string type)

Chain속성을 가진 delegate는 한번 호출될 때 연결된 모든 함수를 순차적으로 호출한다.

추가로 invoke를 사용한 호출도 가능하다.

using System;
using System.Collections.Generic;
using System.Text;

namespace ChainMulticastApp {

    public class CMain {
        public delegate void Delegate(int i, int j);

        static void Main17() {
            Delegate m1 = new Delegate(add);
            Delegate m2 = new Delegate(sub);
            Delegate mChain = (Delegate)Delegate.Combine(m1, m2);
            mChain(2, 5);

            Delegate mMultiCast = m2 + m1;
            mMultiCast.Invoke(2, 3);
        }
        public static void add(int a, int b) => Console.WriteLine(a+b);
        public static void sub(int a, int b) => Console.WriteLine(a-b);
}}

+ Recent posts