상세 컨텐츠

본문 제목

델리게이트, 이벤트

C#

by MJ_119 2024. 6. 20. 18:20

본문

델리게이트 : 하나의 클래스 안에 있는 함수들을 관리 감독함.

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using UnityEngine.Experimental.Playables;

public class example : MonoBehaviour
{
    public delegate void ChainFunction(int value);
    ChainFunction chain;

    int power;
    int defence;

    public void SetPower(int value)
    {
        power += value;
        print("power의 값이 " + value + "만큼 증가했습니다. 총 power의 값 : " + power);
    }

    public void SetDefence(int value)
    {
        defence += value;
        print("defence의 값이 " + value + "만큼 증가했습니다. 총 defence 의 값 : " + defence);
    }


    private void Start()
    {
        chain += SetPower;  // 추가
        chain += SetDefence;

        chain -= SetDefence; // 제거

        chain(5); // SetPower, SetDefence 둘다 5가 들어가서 실행 됨.

        // 여러가지 함수를 한번에 호출함
    }
}

 

 

델리게이트(Delegate)는 C#에서 메서드를 참조하는 형식 안전한 방법을 제공합니다. 델리게이트는 마치 C나 C++에서의 함수 포인터처럼 동작하지만, 형식 안전성을 보장합니다. 델리게이트는 다음과 같은 주요 개념을 포함합니다.

델리게이트의 주요 개념

  1. 정의:
    • 델리게이트는 특정 메서드에 대한 참조를 저장할 수 있는 형식입니다.
    • 델리게이트는 메서드의 시그니처(반환형과 매개변수의 타입)를 정의합니다.
  2. 선언 및 인스턴스화:
    • 델리게이트는 클래스 외부 또는 내부에서 선언할 수 있으며, 인스턴스를 생성하여 특정 메서드를 참조할 수 있습니다.
  3. 호출:
    • 델리게이트 인스턴스를 통해 참조된 메서드를 호출할 수 있습니다.
    • 델리게이트는 멀티캐스트(Multicast) 델리게이트로 여러 메서드를 참조할 수 있습니다.

C#에서 델리게이트 사용 예시

1. 델리게이트 선언 및 사용

using System;

namespace DelegateExample
{
    // 델리게이트 선언
    public delegate void MyDelegate(string message);

    class Program
    {
        // 델리게이트가 참조할 메서드
        public static void ShowMessage(string message)
        {
            Console.WriteLine(message);
        }

        static void Main(string[] args)
        {
            // 델리게이트 인스턴스 생성 및 메서드 참조
            MyDelegate del = new MyDelegate(ShowMessage);

            // 델리게이트를 통해 메서드 호출
            del("Hello, World!");

            // 델리게이트 인스턴스 직접 호출
            del.Invoke("Hello again!");
        }
    }
}

 

 

 

2. 멀티캐스트 델리게이트

하나의 델리게이트 인스턴스에 여러 메서드를 할당할 수 있습니다.

using System;

namespace MultiDelegateExample
{
    // 델리게이트 선언
    public delegate void MyDelegate(string message);

    class Program
    {
        // 첫 번째 메서드
        public static void ShowMessage1(string message)
        {
            Console.WriteLine("Message 1: " + message);
        }

        // 두 번째 메서드
        public static void ShowMessage2(string message)
        {
            Console.WriteLine("Message 2: " + message);
        }

        static void Main(string[] args)
        {
            // 델리게이트 인스턴스 생성 및 여러 메서드 참조
            MyDelegate del = new MyDelegate(ShowMessage1);
            del += ShowMessage2;

            // 델리게이트를 통해 모든 참조된 메서드 호출
            del("Hello, World!");

            // 델리게이트에서 메서드 제거
            del -= ShowMessage1;
            del("Hello again!");
        }
    }
}

 

3. 델리게이트를 사용한 콜백 메서드

using System;

namespace CallbackExample
{
    // 델리게이트 선언
    public delegate void ProcessCompleted();

    class Program
    {
        // 작업을 수행한 후 콜백 메서드를 호출하는 메서드
        public static void PerformTask(ProcessCompleted callback)
        {
            Console.WriteLine("Task in progress...");
            System.Threading.Thread.Sleep(2000); // 작업 시뮬레이션
            Console.WriteLine("Task completed.");

            // 콜백 메서드 호출
            callback();
        }

        // 콜백 메서드
        public static void TaskDone()
        {
            Console.WriteLine("Callback: Task is done!");
        }

        static void Main(string[] args)
        {
            // 작업 수행 및 콜백 메서드 전달
            PerformTask(TaskDone);
        }
    }
}

델리게이트의 장점

  1. 유연성:
    • 델리게이트를 사용하면 런타임에 메서드를 동적으로 할당하고 호출할 수 있습니다.
  2. 코드 재사용성:
    • 동일한 델리게이트 형식을 여러 메서드에 대해 사용할 수 있어 코드의 재사용성이 높아집니다.
  3. 이벤트 처리:
    • 델리게이트는 이벤트 기반 프로그래밍에서 이벤트 핸들러를 설정하는 데 사용됩니다.
  4. 콜백 구현:
    • 비동기 작업 완료 후 특정 메서드를 호출하는 콜백 메서드를 쉽게 구현할 수 있습니다.

 

@ 이벤트 : 델리게이트를 받아서 사용하는 이벤트는 다른 클래스까지 관리 감독 가능.

 example 스크립트

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using UnityEngine.Experimental.Playables;

public class example : MonoBehaviour
{
    public delegate void ChainFunction(int value);
    public static event ChainFunction OnStart;

    int power;
    int defence;

    public void SetPower(int value)
    {
        power += value;
        print("power의 값이 " + value + "만큼 증가했습니다. 총 power의 값 : " + power);
    }

    public void SetDefence(int value)
    {
        defence += value;
        print("defence의 값이 " + value + "만큼 증가했습니다. 총 defence 의 값 : " + defence);
    }


    private void Start()
    {
        OnStart += SetPower;  // 추가
        OnStart += SetDefence;

        OnStart -= SetDefence; // 제거

        // OnStart(5); // SetPower, SetDefence 둘다 5가 들어가서 실행 됨.

        // 여러가지 함수를 한번에 호출함
    }

    private void OnDisable()
    {
        OnStart(5);
    }
}

 


 example2 스크립트

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class example2 : MonoBehaviour
{
    public void Abc(int value)
    {
        print(value + " 값이 증가했습니다.");
    }
    // Start is called before the first frame update
    void Start()
    {
        example.OnStart += Abc;
    }
}

 

 

 

'C#' 카테고리의 다른 글

인터페이스(interface)  (0) 2024.06.21
프로퍼티(property)  (0) 2024.06.21
구조체(Struct), 열거형(enum)  (0) 2024.06.19
arrayList, List, Hashtable, Dictionary, Queue, Stack  (0) 2024.06.19
C# 메서드 정의  (0) 2023.07.04

관련글 더보기