🔗 출처: https://learn.microsoft.com/en-us/dotnet/api/system.eventhandler?view=net-8.0
보통 유니티보다는 윈폼에서 더 많이 쓰인다고 한다.
미리 선언된 델리게이트, 이벤트 용도
코드를 보면 이벤트 핸들러 자체가 이미 델리게이트로 정의되어 있다는 것을 알 수 있다.
namespace System
{
public delegate void EventHandler(object sender, EventArgs e);
}
이 이벤트 핸들러를 사용하는 예를 보자
...
using System; // 꼭 선언해줘야 함
public class TestEventHandler : MonoBehaviour
{
public event EventHandler eventHandler;
void Start()
{
eventHandler += Test;
eventHandler.Invoke(this, EventArgs.Empty);
}
void Test(object o, EventArgs e)
{
Debug.Log("TEST");
}
}
EventArgs (이벤트 아규먼트)는 뭐지?! 전달하고 싶은 정보를 전달할 때 사용하면 되고, 없으면 EventArgs.Empty
를 사용하면 된다.
namespace System
{
public class EventArgs
{
public static readonly EventArgs Empty;
public EventArgs();
}
}
이를 십분 활용하는 방법을 더 생각해보자면 아래처럼 상속을 활용할 수 있다.
public class EventTest1 : EventArgs
{
public string _name;
public EventTest(string name)
{
_name = name;
}
}
public class TestDelegate : MonoBehaviour
{
public event EventHandler eventHandler;
void Start()
{
EventTest1 eventTest = new EventTest1("EventTest1");
eventHandler += Test;
eventHandler.Invoker(this, (EventArgs)eventTest);
}
void Test(object o, EventArgs e)
{
Debug.Log((EventTest1)e)._name);
}
}