아카이빙/C#

[C#] Delegate는 언제 사용하는가

셩님 2018. 6. 25. 15:56

[C#] Delegate는 언제 사용하는가

  • 대표적으로 메소드를 매개변수로 넘기고 싶을때

  • 정렬 시, 비교 루틴을 매개변수로 넣어보자.

Delegate 선언

delegate int Compare<T>(T a, T b);

오름차순, 내림차순 메소드

static int AscendCompare<T>(T a, T b) where T : IComparable<T>
{
return a.CompareTo(b);
}

static int DescendCompare<T>(T a, T b) where T : IComparable<T>
{
return a.CompareTo(b) * -1;
}

Compare delegate를 매개변수로 받는 정렬 메소드

static void BubbleSort<T>(T[] dataSet, Compare<T> Comparer)
{
   T temp;

   for(int i=0; i<dataSet.Length -1; i++)
  {
       for(int j=i+1; j<dataSet.Length; j++)
      {
           if(Comparer(dataSet[i], dataSet[j]) > 0)
          {
               temp = dataSet[i];
               dataSet[i] = dataSet[j];
               dataSet[j] = temp;
          }
      }
  }
}

메인

static void PrintArray<T>(T[] arr)
{
   System.Array.ForEach(arr, (x) => Console.Write("{0} ", x));
   Console.WriteLine();
}

static void Main()
{
   int[] arr = {3, 15, 7, 28, 1};

   Console.WriteLine("Sorting ascending...");
   BubbleSort<int>(arr, new Compare<int>(AscendCompare));
   PrintArray<int>(arr);

   string[] arr2 = {"apple", "microsoft", "blizzard", "samsung", "nike"};

   Console.WriteLine("Sorting Descending...");
   BubbleSort<string>(arr2, new Compare<string>(DescendCompare));
   PrintArray<string>(arr2);
}

Sorting ascending...
1 3 7 15 28
Sorting Descending...
samsung nike microsoft blizzard apple

참조

  • 뇌를 자극하는 C# 5.0 프로그래밍, 박상현, 한빛미디어 


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

[C#] 이벤트와 델리게이트  (0) 2018.06.25
[C#] Delegate와 익명메소드  (0) 2018.06.25
[C#] Delegate (대리자)  (0) 2018.06.25
[C#] 예외처리  (0) 2018.06.21
[C#] 제네릭의 형식 제약  (0) 2018.06.21