1. delegate
    □ 개념
    □ 예시

📝 delegate (대리자)

1. 개념

메서드에 대한 참조를 나타내는 형식

C++의 함수 포인터와 비슷하게 동작함!

           ■함수포인터?

           : 함수의 시작 주소를 가리키는 포인터

           : 함수를 간접적으로 호출할 수 있게 해주는 변수

 

참조

하나 이상의 메서드를 참조할 수 있다.

참조할 메서드는 같은 반환값과 같은 매개변수를 가져야 한다.

□ += 연산자로 메서드 추가, -= 연산자로 메서드 제거가 가능하다.

 

호출

 메서드를 직접 호출하지 않고 메서드를 참조하고 있는 델리게이트를 통해 호출한다.

 델리게이트를 실행하면 참조하고 있는 모든 메서드가 실행된다.

 

📝 예시 

// 델리게이트
public delegate void Attack(float damage);
public class AttackHandler
{
    public Attack OnTtack;

    public void AttackExcute(float damage)
    {
        OnTtack?.Invoke(damage);
    }

    public void AddToAttack(Attack attck) 
    {
        OnTtack += attck;
    }
}

public class Player
{
    public float hp;
    public float damage;

    public Player(float hp,float d) 
    {
        this.hp = hp;
        this.damage = d;
    }

    public void GetAttack(float damage) 
    {
        hp -= damage;
        Console.WriteLine($"{damage} 데미지를 얻었습니다.");
    }
}

public class SystemAlarm
{
    public void UpdateUi(float damage) 
    {
        Console.WriteLine($"player가 {damage} 를 입었습니다.");
    }
}
    static void Main(string[] args)
    {
        // 
        AttackHandler AKHandler = new AttackHandler();

        // 인스턴스 생성
        Player player = new Player(10f, 3f);
        SystemAlarm alarm = new SystemAlarm();

        AKHandler.AddToAttack(player.GetAttack);
        AKHandler.AddToAttack(alarm.UpdateUi);

        // 델리게이트 실행
        AKHandler.AttackExcute( 7f );
    }

Attack 델리게이트

           float 매개변수를 받는 메서드들을 참조하는 형식

            float 매개변수를 받는 Player와 SystemAlarm 메서드 등록

  AttackExcute 호출 시 두 메서드가 순차적으로 실행

 

출력


함수포인터

https://www.tcpschool.com/cpp/cpp_function_pointer

 

코딩교육 티씨피스쿨

4차산업혁명, 코딩교육, 소프트웨어교육, 코딩기초, SW코딩, 기초코딩부터 자바 파이썬 등

tcpschool.com

델리게이트

https://learn.microsoft.com/ko-kr/dotnet/csharp/programming-guide/delegates/using-delegates

 

대리자 사용 - C#

대리자를 사용하는 방법을 알아봅니다. 대리자는 메서드를 안전하게 캡슐화하는 개체 지향적이고 형식이 안전하며 보안이 유지되는 형식입니다.

learn.microsoft.com

 

+ Recent posts