프로그래밍/C#

[C#] 대리자 (Delegate) - 델리게이트

QA Engineer - P군 2016. 9. 25. 21:54
반응형

대리자 [Delegate]

대리자는 특정 매개 변수 목록 및 반환 형식이 있는 메서드에 대한 참조를 나타내는 형식입니다. 대리자를 인스턴스화하면, 호환되는 시그니처와 반환 형식을 가진 모든 메서드를 대리자 인스턴스에 연결할 수 있습니다. 대리자 인스턴스를 통해 메서드를 호출할 수 있습니다.
대리자는 메서드를 다른 메서드에 인수로 전달하는 데 사용됩니다. 이벤트 처리기는 대리자를 통해 호출되는 메서드라고 할 수 있습니다. 사용자 지정 메서드를 만들면 Windows 컨트롤 같은 클래스가 특정 이벤트가 발생했을 때 해당 메서드를 호출할 수 있습니다.  

 

대리자는 다음과 같은 특징을 가지고 있습니다.

 

1. 대리자는 C++의 함수 포인터와 유사하지만 형식이 안전합니다.

2. 대리자를 통해 메서드를 매개 변수로 전달할 수 있습니다.

3. 대리자를 사용하여 콜백 메서드를 정의할 수 있습니다.

4. 여러 대리자를 연결할 수 있습니다. 

5. 메서드와 대리자 형식이 정확히 일치할 필요는 없습니다. 

 

델리게이트는 다음과 같은 형식을 가지고 있습니다.

 

1
public delegate int PerformCalculation(int x, int y);
cs

 

간단하게 델리게이트를 사용해보겠습니다.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
public delegate void Del(string message);
 
public static void DelegateMethod(string message)
{
    System.Console.WriteLine(message);
}
 
static void Main(string[] args)
{
    Del Handler = DelegateMethod;
 
    Handler("Hello! World!");         
}
cs

 

[결과]

 

C++의 함수 포인터와 아주 흡사합니다. 사용법도 그렇구요..

 

델리게이트는 매개변수로 사용이 가능합니다. 

(대리자를 통해 메서드를 매개 변수로 전달할 수 있습니다.)

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public delegate void Del(string message);
 
public static void DelegateMethod(string message)
{
    System.Console.WriteLine(message);
}
 
public static void MethodWithCallback(string param1, string param2, Del callback)
{
    callback("Mesage : " + (param1 + param2).ToString());
}
        
static void Main(string[] args)
{
    Del Handler = DelegateMethod;
 
    MethodWithCallback("Hello!""World !", Handler);
        
}
 

 

[결과]

 

델리게이트는 호출 목록에 다른 델리게이트를 더하거나 뺄 수 있습니다. 

(여러 대리자를 연결할 수 있습니다. )

 

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
32
33
34
35
36
37
38
public class MethodClass
{
    public void Method1(string message) 
    {
        Console.WriteLine("Method1 = " + message);
    }
    public void Method2(string message) 
    {
        Console.WriteLine("Method2 = " + message);
    }
}
 
class Program
{
      
public delegate void Del(string message);
 
public static void DelegateMethod(string message)
{
    System.Console.WriteLine("DelegateMethod  = " + message);
}
 
static void Main(string[] args)
{
    MethodClass obj = new MethodClass();
    Del d1 = obj.Method1;
    Del d2 = obj.Method2;
    Del d3 = DelegateMethod;
 
    Del allMethodsDelegate = d1 + d2;
    allMethodsDelegate += d3;
 
    allMethodsDelegate("Send Message 1 ");
 
    allMethodsDelegate -= d1;
 
    allMethodsDelegate("Send Message 2");
}
cs

 

[실행 결과]

 

 

매개변수로 전달시에는 정확한 타입을 명시하지 않아도 됩니다.

(메서드와 대리자 형식이 정확히 일치할 필요는 없습니다. )

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
delegate void Delegate1();
delegate void Delegate2();
 
static void method(Delegate1 a, Delegate2 b, System.Delegate c)
{
    System.Console.WriteLine(a == c);
    System.Console.WriteLine(b == c);
}
 
static void DelegateMethod()
{
 
}
 
static void Main(string[] args)
{
    Delegate1 del_1 = DelegateMethod;
    Delegate2 del_2 = DelegateMethod;
 
    method(del_1, del_2, del_2);        
}
cs

 

[결과]

 

 

[참고]

대리자 사용(C# 프로그래밍 가이드) [MSDN] - 

https://msdn.microsoft.com/ko-kr/library/ms173172.aspx

반응형