[C# 객체지향] Anonymous Method

eunjin lee·2022년 9월 12일
0

C# 9.0 프로그래밍

목록 보기
25/50

델리게이트에 전달되는 메서드가 일회성으로만 필요할 때 Anonymous Method를 만들어 사용한다.


익명 메서드를 사용하지 않으면 아래의 코드와 같이 메서드를 정의하여 매개변수로 넘긴다.
✍ 샘플코드

    {
        static void Main(string[] args)
        {
            Thread t = new Thread(ThreadFunc);
            t.Start();
        }

        static void ThreadFunc(object obj)
        {
            Console.WriteLine("ThreadFunc called.");
        }
    }

이를 익명 메서드로 바꾸면 아래의 코드와 같다.

        static void Main(string[] args)
        {
            Thread t = new Thread(delegate (object obj) { Console.WriteLine("DelegateThreadFuncCalled"); });
            t.Start();
        }

0개의 댓글