C#

[C#] - 델리게이트(delegate), 멀티캐스트 델리게이트

Riucc 2019. 4. 8. 23:09

○ 델리게이트(delegate), 멀티캐스트 델리게이트

 

- delegate(델리게이트)

     본질은 메소드 참조형

     복수 또는 단일 메소드를 대신하여 호출하는 역할 -> 같은 형식이어야 한다

     -> 다수의 메소드 호출 시 각각 해주는 것보다 한 번 호출로 한 방에 끝내자는 의도

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


1
2
3
4
// 델리게이트 형식 

[접근 한정자] delegate return형 델리게이트형명(메소드 매개변수); 
ex) delegate int DelegateType(String Name);

// 델리게이트 사용
DelegateType DelegateMethod = Function; // C# 2.0 버전
cs


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
delegate void DelegateType(string str);
 
class A 
{
    public void Print(string str)
    {
        Console.WriteLine(str);
    }
}
 
A test = new A();
DelegateType DelMethod1 = new DelegateType(test.Print);
DelMethod1("HI EVERYONE"); // C# 1.0 버전
 
DelegateType DelMethod2 = test.Print;
DelMethod2("2.0버전이닷"); // C# 2.0 버전
 
cs


- multicast delegate(멀티캐스트 델리게이트)

     다수 또는 단일 메소드 호출

     호출할 메소드 포함할 때 +=, 호출할 메소드 제거할 때 -= 


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
    
delegate void DelegateType();
class A
{
   public void PrintBanana()
   {
       Console.WriteLine("Banana");
   }
   public void PrintApple()
   {
       Console.WriteLine("Apple");
   }
   public void PrintGrape()
   {
       Console.WriteLine("Grape");
   }
}
 
A test = new A();
DelegateType Del = test.PrintApple;
Del += test.PrintBanana;
Del += test.PrintGrape;
Del();  // Apple Banana Grape 출력
Del -= test.PrintBanana;
Del(); // Apple Grape 
cs