Delegate, event & action (1)

정제로·2023년 9월 15일
0

C#

목록 보기
28/30

저에게 너무 어려운 내용입니다.. 틀린점 있거나 다른 참고할 만한 블로그 있으면 댓글 부탁드립니다... 뉴비절단기 델리게이트 멈춰!!

Delegate

한마디로 요약하자면, 매개변수로 함수로 받고싶을때 사용한다.
보통은 매개변수로는 자료형을 받지만, 델리게이트를 사용하면 매개변수로 함수를 받을 수 있다.

Delegate vs Event

delegateevent
함수를 저장해서 실행한다.
어떤 요청을 햇을때, 그 결과를 처리하는것을 만들 수 있다(콜백)이벤트를 예약해두고 필요할때 해당기능들을 실행(구독)
등록한 이벤트를 외부에서 실행 가능등록한 이벤트는 외부에서 실행불가

배열로 델리게이트 사용

아래와 같은 코드가 있다

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Test
{ 
    class Calc
    {
        public int PrintSum (int a, int b)
        {
            return a + b;
        }

        public int PrintMultiple (int a, int b)
        {
            return a * b;
        }

        static void Main()
        {
            Calc calc = new Calc();

            int first = 210;
            int second = 3;

            Console.WriteLine($"sum = {calc.PrintSum(first, second)}");
            Console.WriteLine($"multiple = {calc.PrintMultiple(first, second)}");
        }
    }
}

당연히 출력이 잘 될것이다.
하지만, 예를들어, 나눗셈, 루트, 제곱 등을 구하는 함수가 추가된다면,
계쏙 저렇게 추가해서 출력해주기가 힘들것이다.

그럴때 빠르게 추가할수 잇는 방법이 있다.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Test
{ 
    class Calc
    {
        delegate int CalculateMethodDelegate (int a, int b);

        public static int PrintSum (int a, int b)
        {
            return a + b;
        }

        public static int PrintMultiple (int a, int b)
        {
            return a * b;
        }

        public static int PrintDevide(int a, int b)
        {
            return a / b;
        }

        static void Main()
        {
            CalculateMethodDelegate[] calcDele = { PrintSum, PrintMultiple, PrintDevide };

            int first = 210;
            int second = 3;

            for (int i = 0; i < calcDele.Length; i++)
            {
                Console.Write(calcDele[i](first, second) + "\n");
            }
        }
    }
}

이렇게 델리게이트를 배열화 해서 배열처럼 사용도 가능하다.
델리게이트의 응용방법은 정말 무궁무진하다..

함수 여러개 받아서 사용

아래와 같은 코드가 있다

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Test
{ 
    class Calc
    {
        static int power = 5;
        static int defence = 10;

        public static void LvUpPowerUp(int value)
        {
            Console.WriteLine($"현재 Power : {power}");
            power += value;
            Console.WriteLine($"Power가 {value}만큼 증가했습니다. \n현재 Power : {power}");
            Console.WriteLine();
        }

        public static void LvUpDefenceUp(int value)
        {
            Console.WriteLine($"현재 Defence : {defence}");
            defence += value;
            Console.WriteLine($"Defence가 {value}만큼 증가했습니다. \n현재 Defence : {defence}");
        }

        static void Main()
        {
        	LvUpPowerUp(5);
            LvUpDefenceUp(5);
        }
    }
}

이러면 함수를 사용할 수 있다.
하지만 위 예제와 마찬가지로 함수가 점점 늘어난다면?
그럴땐 함수를 합치자!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Test
{ 
    class Calc
    {
        delegate void LvUpDele(int a);

        static int power = 5;
        static int defence = 10;

        public static void LvUpPowerUp(int value)
        {
            Console.WriteLine($"현재 Power : {power}");
            power += value;
            Console.WriteLine($"Power가 {value}만큼 증가했습니다. \n현재 Power : {power}");
            Console.WriteLine();
        }

        public static void LvUpDefenceUp(int value)
        {
            Console.WriteLine($"현재 Defence : {defence}");
            defence += value;
            Console.WriteLine($"Defence가 {value}만큼 증가했습니다. \n현재 Defence : {defence}");
        }

        static void Main()
        {
            LvUpDele lvUpDele;
            lvUpDele = new LvUpDele(LvUpPowerUp);
            lvUpDele += LvUpDefenceUp;
            lvUpDele(5);
        }
    }
}

계속해서 += 연산자를 통해 델리게이트에 함수를 추가해줄수 있다.
그리고 호출하면, 그 안에 들어있던 함수 전부가 호출된다

마찬가지로 델리게이트에 있던 함수를 -=연산자를 이용해서 제거할수도 있다

이벤트

이벤트는 예약과 구독을 사용한다
일명 옵저버패턴이라고 불린다.
기능을 += 으로 예약해놓고, 필요할때 호출하는 식이다.

아래와 같은 코드가 있다.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Test
{
    class Calc
    {
        public delegate void LvUpDele(int a);
        public static event LvUpDele OnLvUp; //추가

        static int power = 5;
        static int defence = 10;

        public static void LvUpPowerUp(int value)
        {
            Console.WriteLine($"현재 Power : {power}");
            power += value;
            Console.WriteLine($"Power가 {value}만큼 증가했습니다. \n현재 Power : {power}");
            Console.WriteLine();
        }

        public static void LvUpDefenceUp(int value)
        {
            Console.WriteLine($"현재 Defence : {defence}");
            defence += value;
            Console.WriteLine($"Defence가 {value}만큼 증가했습니다. \n현재 Defence : {defence}");
        }

        static void Main()
        {
            OnLvUp += LvUpPowerUp;
            OnLvUp += LvUpDefenceUp;
        }
    }
}

이렇게 이벤트를 델리게이트에 추가해주고, 다른스크립트에 함수를 만들어서 해당 이벤트에 추가해보자

using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using Test;

namespace Test
{
    public class Solution
    {
        public static void LvUpHp(int value)
        {
            Console.WriteLine($"{value} 만큼 올랐다");
        }

        static void Coms()
        {
            Calc.OnLvUp += LvUpHp;
        }

    }
}

이런 코드를 추가했다
그러고 다시 돌아와서 Main에
Solution.Coms();를 추가해주었다..

그러고 실행을 하면?

완료!

profile
초보자입니다.. 잘못된 정보, 달게 받겠습니다..

0개의 댓글

관련 채용 정보