Delegate란?
method signature(return type and parameters)를 정의하는 참조형식의 data type이다.
함수의 parameter로 전달될 수 있다.
Delegate는 아래 3단계로 동작한다.
1. Declare a delegate, 델리게이트 선언
Delegate syntax
[access modifier] delegate [return type] [delegate name]([parameters])string parameter와 void return type을 가지는 MyDelegate라는 이름의 delegate를 선언했다.
public delegate void MyDelegate(string msg);delegate는 class 내부, 외부에서 모두 선언 가능하지만, class밖에서 선언되어야 한다.
2. Set a target method, 함수 구현
target method나, lambda expression을 설정한다.
public delegate void MyDelegate(string msg); // declare a delegate
// set target method
MyDelegate del = new MyDelegate(MethodA);
// or 
MyDelegate del = MethodA; 
// or set lambda expression 
MyDelegate del = (string msg) =>  Console.WriteLine(msg);
// target method
static void MethodA(string message)
{
    Console.WriteLine(message);
}3. Invoke a delegate, 델리게이트 실행
Invoke() 함수나, () operator를 이용해서 실행한다.
del.Invoke("Hello World!");
// or 
del("Hello World!");Delegate Parameter
함수는 parameter로 delegate type을 가질 수 있다.
함수는 다른 함수의 parameter로 전달 할 수 없다. 아래와 같이 compile error가 발생한다.

하지만, delegate는 함수의 parameter로 전달할 수 있다.
        public delegate int Manipulate(int a);
        public static int NormalMethod(int a)
        {
            return a * 2;
        }
        //public static int RunAnotherMethod(NormalMethod theMethod)
        //{
        //    return 0;
        //}
        public static int RunAnotherMethod(Manipulate theMethod, int a)
        { 
            return theMethod(a);
        }
        static void Main(string[] args)
        {
            //Invoking a normal method
            var b = NormalMethod(2);
            
            //Create an instance of the delegate
            Manipulate normalMethodDelegate = new Manipulate(NormalMethod);
            int normalResult = normalMethodDelegate(3);
            //Pass a delegate method as a variable
            int anotherResult = RunAnotherMethod(normalMethodDelegate, 4);
        }Multicast Delegate
delegate는 복수개의 함수를 가리킬 수 있다.
        MyDelegate del1 = ClassA.MethodA;
        MyDelegate del2 = ClassB.MethodB;
        MyDelegate del = del1 + del2; // combines del1 + del2Generic Delegate
generic type의 parameter와 return type을 가지는 delegate를 정의할 수 있다.
public delegate T add<T>(T param1, T param2); // generic delegate
Built-in Generic Delegate
C#은 Func, Action이라는 built-in generic delegate type을 포함한다.
2개의 int type input과 int type return을 갖는 Func delegate이다.
Func delegate는 다른 type의 0 ~ 16개의 input parameter를 가질 수 있다.
Func<int, int, int> sum;Func with an Anonymous Method
delegate keyword를 사용하여 Func delegate에 무명함수를 할당할 수 있다.
Func<int> getRandomNumber = delegate()
                            {
                                Random rnd = new Random();
                                return rnd.Next(1, 100);
                            };Func with Lambda Expression
Func<int> getRandomNumber = () => new Random().Next(1, 100);
//Or 
Func<int, int, int>  Sum  = (x, y) => x + y;
'C#' 카테고리의 다른 글
| C#] DynamicObject Class VS ExpandoObject Class (0) | 2022.07.07 | 
|---|---|
| C#] Expression trees 설명, Delegate와 차이점 (0) | 2022.07.06 | 
| C#] 코드 성능 분석 BenchmarkDotNet (1) | 2022.07.05 | 
| C#] Anonymous Type(무명 형식) 정의, 사용법, Dynamic Type과 비교 (1) | 2022.06.28 | 
| YouTube Data API ] 재생목록의 동영상리스트 데이터 가져오기 (0) | 2022.06.17 | 
 
										
									 
										
									 
										
									 
										
									
댓글