본문 바로가기
프로그램/C# 1000제

C# 예제5] C# 프로그래밍 입문 CHAPTER 1. p28 델리게이트

by 건티 2021. 7. 16.
728x90

델리게이트(delegate)란 메소드를 참조하기 위한 방법론으로 C#에서는 주로 이벤트와 스레드를 처리하기 위한 프로그래밍 기법으로 사용된다. 델리게이트는 C/C++언어에서의 함수 포인트(function pointer)와 유사한 기능을 제공하지만 함수 포인터보다는 객체 지향적이며 타입이 안정적이다.

델리게이트를 정의하고 델리게이트의 객체를 생성하는 것은 기본적으로 클래스를 정의하고 클래스의 객체를 만드는 것과 비슷하지만 델리게이트 객체를 통하여 메소드를 호출한다는 점이 특징적이다.

 

참고예제]

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

namespace Chapter1
{
    delegate void SampleDelegate(); //델리게이트 정의
    class DelegateClass
    {
        public void DelegateMethod() //델리게이트할 메소드
        {
            Console.WriteLine("In the DelegateClass.DelegateMethod ...");
        }

    }
    class DelegateApp
    {
        public static void Main()
        {
            DelegateClass obj = new DelegateClass();
            SampleDelegate sd = new SampleDelegate(obj.DelegateMethod);
            sd(); //invoke obj.DelegateMethod() indirectly.
        }
    }
}

 

참고예제 결과]

 

 

 

대한민국의 아름다운 영토, 독도

 

반응형

댓글