더북(TheBook)

이름 없는 메서드를 대신 호출

delegate 키워드를 사용하면 이름이 없는 메서드를 생성한 후 해당 메서드를 대신 호출할 수 있습니다.

이름 없는 메서드를 대신 호출: AnonymousDelegate.cs

using System;

class AnonymousDelegate
{
    delegate void SayDelegate();
    static void Main()
    {
        //delegate 키워드로 함수를 바로 정의해서 사용
        SayDelegate say = delegate ()
        {
            Console.WriteLine("반갑습니다.");
        };
        say();
    }
}

실행 결과

반갑습니다.

이 코드는 익명 메서드 또는 무명 메서드라고 하는 메서드를 delegate 키워드로 만들고, 이를 SayDelegate 개체로 대신 호출합니다. 잠시 후에 무명 메서드를 다시 살펴보겠습니다.