유니티

c# delegate(델리게이트)

공대녀J 2022. 10. 4. 12:55
public enum NetEventType
{
    Connect=0,
    Disconnect,
    SendError,
    ReceiveError,
}

public enum NetEventResult
{
    Failure=-1,
    Success=0,
}

public class NetEventState
{
    public NetEventType type;
    public NetEventResult result;
}

public delegate void EventHandler(NetEventState state); //델리게이트 선언
private EventHandler m_handler; //델리게이트의 인스턴스 생성

...

public void EventCallback(NetEventState state)
{
    ....
}

m_handler += EventCallback; // 여러 함수 추가 가능.

NetEventState state = new NetEventState();

m_handler(state); //델리게이트 호출. 추가해준 함수들을 순서대로 실행.

m_handler -= EventCallback; //저장된 함수 삭제

c#에서 델리게이트는 c++에서 함수 포인터와 유사한 의미를 갖는다.

delegate void Del(string str); 과 같이 델리게이트를 선언해준 경우,

void 반환형을 갖고 string 타입의 매개변수를 갖는 함수를 저장할 수 있는 Del 자료형을 생성해준 것과 같다.

따라서 Del d; 은 Del 타입의 d라는 이름을 가진 인스턴스를 생성해준 것이다.