본문 바로가기

C#/Study

[복습] Delegate - C#, CSharp, 씨샵, 델리게이트, 대리자

반응형

Delegate란?

  • 사용방법
delegate [반환형식] [대리자이름](매개변수_목록)
delegate int MyDelegate(int a, int b);
  • Delegate는 인스턴스가 아닌 형식(Type)이다.
  • 위의 예시에 있는 MyDelegate는 int, string과 같은 형식이며, "메서드를 참조하는 그 무엇"을 만들려면 MyDelegate의 인스턴스를 따로 만들어야 한다.

 

예제 - delegate의 덧셈, 뺄셈 메서드 참조

delegate int TestDelegate(int a, int b);

class Calculator
{
    public int Plus(int a, int b)
    {
        return a + b;
    }

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

class Program
{
    static void Main(string[] args)
    {
        Calculator calculator = new Calculator();
        TestDelegate testDelegate;

        testDelegate = new TestDelegate(calculator.Plus);
        Console.WriteLine(testDelegate(3, 4));

        testDelegate = new TestDelegate(Calculator.Minus);
        Console.WriteLine(testDelegate(7, 5));
    }
}
  • Delegate는 static 메서드도 참조할 수 있다.

 

예제 - 정렬 메서드 작성

  • 정렬 메서드를 작성한 클래스
class ClassEx2
{
    public static int AscendCompare(int a, int b)
    {
        if (a > b) return 1;
        else if (a == b) return 0;
        else return -1;
    }

    public static int DescendCompare(int a, int b)
    {
        if (a < b) return 1;
        else if (a == b) return 0;
        else return -1;
    }

    public static void BubbleSort(int[] dataSet, Compare compare)
    {
        int i = 0;
        int j = 0;
        int temp = 0;

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

 

  • 해당 delegate는 namespace와 클래스 사이에 선언해준다.

 

  • 메인 메서드
int[] array = { 3, 7, 4, 2, 10 };

Console.WriteLine("-- 오름차순 정렬 --");
ClassEx2.BubbleSort(array, new Compare(ClassEx2.AscendCompare));

for (int i = 0; i < array.Length; i++)
{
    Console.Write($"{array[i]} ");
}

int[] array2 = { 7, 2, 8, 10, 11 };
Console.WriteLine("\n-- 내림차순 정렬 --");
ClassEx2.BubbleSort(array2, new Compare(ClassEx2.DescendCompare));

for (int i = 0; i < array2.Length; i++)
{
    Console.Write($"{array2[i]} ");
}

Console.WriteLine();

반응형