Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

For me

[Unity] 2) Delegate 와 Event 본문

Unity/이론

[Unity] 2) Delegate 와 Event

GiveZero 2023. 2. 28. 18:25

Delegate

의미

Delegate (위임하다), 대리자

 

delegate의 본질은 메소드 참조형

메소드를 참조해서 동작할 수 있도록 함

즉, 함수의 별명으로써 뭔가 할 수 있도록 하는 역할을 함 

형식과 사용

복수 또는 단일 메소드를 대신하여 호출 하는 역할 ( 같은 역할이여야 함 → 매개변수, return값이 같아야함)

메소드만 호출 가능

외부에서 호출 가능 (private protected 메소드 호출 불가)

 

delegate 선언

[접근 한정자] delegate return형 delegate명 (메소드 매개변수);

 *예시 delegate int DelegateType(string Name); 

 

Delegate의 사용 예시

(C# 1.0 이상)

Delegate형 Delegate명 = new Delegate형(호출할 메소드)

 

                                              ↓ (C# 2.0 이상에서 사용가능함 ) 좀더 간편해짐

 

DelegateType Delegate명 = 호출할Function;

namespace Stduy
{
	delegate void DelegateType(string str);
    
    class A
    {
    	public void Print(string str)
        {
			Console.WriteLine(str);
        }
    }
    
    class Program
    {
    	static void Main(string[] args)
        {
        	A Test = new A();
            DelegateType DelMethod01 = new DelegateType(Test.print);  // C# 1.0
            DelMethod1("Hello World");
            
            DelegateType DelMethod2 = Test.Print;		// C# 2.0
            DelMethod2("HelloWorld");
        }
    }
          
}

 

multicast 델리게이트

데이터를 여러 사용자에게 동시에 보냄

 

역할

다수 또는 단일 메소드 호출

+= , -= 사용하여 호출할 메소드 포함 또는 제거

namespace Stduy
{
	delegate void DelegateType(string str);
    
    class A
    {
    	public void PrintA()
        {
			Console.WriteLine("PrintA");
        }
        
        public void PrintB()
        {
			Console.WriteLine("PrintB");
        }
    }
    
    class Program
    {
    	static void Main(string[] args)
        {
        	A Test = new A();
            Delegate DelFunc = Test.PrintA;
            DelFunc += Trest.PrintB;
            DelFunc();
            DelFunc -= Test.PrintB;
            DelFunc();
        }
    }
          
}

 


Event

의미

'중요한 사건' 을 이벤트 라고함

델리게이트 + a의 개념으로 특정 상황이 발생했을 때 알리고자 하는 용도 (호출을 의미 + 데이터)

 

게시자 - 이벤트를 발생시키는 클래스

구독자 - 이벤트를 받거나 처리하는 클래스

 

델리게이트를 기반으로 함 (메소드 호출)

 

이벤트는 메소드 안에서만 사용 가능

형식과 사용

기본형식

[접근 한정자] event Delegate형 Event명

 delegate void DelegateType(string message);
 
 class A
 {
	public event DelegateType EventHandler;
    public void Func(string Message)
    {
    	EventHandler(Message);
    }
 }

메소드 안에서 호출하는 형태로 나열해야함

 

이벤트 메서드 추가 및 삭제

+= , -=

 

namespace Stduy
{
	delegate void DelegateType(string str);
    
    class A
 	{
        public event DelegateType EventHandler;
        
        public void Func(string Message)
        {
            EventHandler(Message);
        }
 	}
    
    class B
    {
    	public void PrintA(string Message)
        {
			Console.WriteLine(Message);
        }
        
        public void PrintB(string Message)
        {
			Console.WriteLine(Message);
        }
    }
    
    class Program
    {
    	static void Main(string[] args)
        {
        	A Test1 = new A();
            B Test2 = new B();
            
            Test1.EventHandler += new DelegateType(Test2.PrintA);
            Test1.EventHandler += new DelegateType(Test2.PrintB);
            Test1.Func("---1");
            Test1.EventHandler -= Test2.PrintB;
            Test1.Func("---2");
            Test1.EventHandler -= Test.PrintA;
            
            Test1.EventHanlder += Test2.PrintA; // 처리기에 추가
            Test1.EventHandler += Test2.PrintB;
            
            Test1.Func("-----3");
        }
    }
 }

=>

---1

---1

---2

----3

----3

 

핵심

이벤트 핸들러에 객체의 메소드를 연결

이벤트 핸들러는 객체 메소드에서 호출

이벤트 핸들러를 포험한 객체 안의 메소드를 통해 다른 객체 또는 같은 객체의 메소드를 호출하기 위한 방법


Delegate 와 Event의 차이

  Delegate Event
공통점 객체의 메소드 호출
차이점 델리게이트 호출 이벤트를 포함한 메소드에서 호출
  델리게이트에 연결 이벤트 핸들러에 연결

'Unity > 이론' 카테고리의 다른 글

[Unity] 6) Addressable  (0) 2023.03.03
[Unity] 5) Nullable  (0) 2023.03.01
[Unity] 4) Reflection 과 Attribute  (0) 2023.02.28
[Unity] 3) Exception  (0) 2023.02.28
[Unity] 1) Invoke 와 Coroutine의 차이  (0) 2023.02.28