C# 델리게이트 delegate

Delegate :

 

"(권한, 업무 등을)위임하다"

라고 영어사전은 말하고 있고,

 

"정적메서드, 클래스의 메서드, 클래스의 인스턴스 메서드를 참조하는 데이터구조"

라고 msdn은 말하고 있다.

 

 

메서드를 겍체 형태로 위임할 수 있는 타입.

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CSTest
{
	delegate void dele();

	class AA
	{
		public void Mth1()
		{
			Console.WriteLine("홀수네");
		}

		public void Mth2()
		{
			Console.WriteLine("홀수구먼");
		}
	}

	class Program
	{
		static void Main(string[] args)
		{
			AA aClass = new AA();
			dele d = null;
			d += aClass.Mth1;
			d += aClass.Mth2;

			Sub(10, d);

		}

		static void Sub(int n, dele d)
		{
			for (int i = 0; i < n; i++)
			{
				Console.WriteLine("{0}", i);
				if (i % 2 == 1)
					d();
			}
		}
	}
}

 

 

 

[네임스페이스, 클래스 내부 둘다 선언 가능하다.]

[null로 초기화가 가능하다.]

[메서드를 add형태로 추가할 수 있다.(배열도 가능)]

[메서드를 인수로 쓸 수 있게 해준다.]

착안점은 메서드를 직접호출한게 아니고 델리게이트(대리자)가 호출했다는 점이다.

이것이 콜백(CallBack)기능을 구현하게 해주며 이벤트와 밀접한 관련이 있다.