익명 함수(C# 프로그래밍 가이드)

업데이트: 2007년 11월

다른 부분에서 설명한 것처럼 대리자는 메서드 호출을 래핑하는 형식입니다. 대리자 인스턴스는 형식과 마찬가지로 메서드 사이에 전달될 수 있으며 메서드처럼 호출될 수 있습니다. 익명 함수는 대리자 형식과 함께 사용될 수 있는 "인라인" 문이나 식입니다. 익명 함수는 명명된 대리자를 초기화하는 데 사용되거나 명명된 대리자 형식 대신 메서드 매개 변수로 전달될 수 있습니다.

익명 함수에는 두 가지 종류가 있으며 각 익명 함수는 다음 단원에서 따로 설명합니다.

C#에서의 대리자 발전 과정

C# 1.0에서는 코드의 다른 부분에 정의된 메서드를 통해 명시적으로 초기화하는 방법으로 대리자의 인스턴스를 만들었습니다. C# 2.0에서는 대리자 호출 시 실행될 수 있는 무명의 인라인 문 블록을 작성하기 위한 방법으로 무명 메서드라는 개념이 도입되었습니다. C# 3.0에는 무명 메서드와 비슷한 개념이지만 표현력이 뛰어나면서 간결한 람다 식이 도입되었습니다. 이러한 두 기능을 통칭하여 익명 함수라고 합니다. 일반적으로 .NET Framework 3.5 이상을 대상으로 하는 응용 프로그램에서는 람다 식을 사용하는 것이 좋습니다.

다음 예제에서는 C# 1.0부터 C# 3.0까지 대리자 생성의 발전 과정을 보여 줍니다.

class Test
{
    delegate void TestDelegate(string s);
    static void M(string s)
    {
        Console.WriteLine(s);
    }

    static void Main(string[] args)
    {
        // Original delegate syntax required 
        // initialization with a named method.
        TestDelegate testdelA = new TestDelegate(M);

        // C# 2.0: A delegate can be initialized with
        // inline code, called an "anonymous method." This
        // method takes a string as an input parameter.
        TestDelegate testDelB = delegate(string s) { Console.WriteLine(s); };

        // C# 3.0. A delegate can be initialized with
        // a lambda expression. The lambda also takes a string
        // as an input parameter (x). The type of x is inferred by the compiler.
        TestDelegate testDelC = (x) => { Console.WriteLine(x); };

        // Invoke the delegates.
        testdelA("Hello. My name is M and I write lines.");
        testDelB("That's nothing. I'm anonymous and ");
        testDelC("I'm a famous author.");

        // Keep console window open in debug mode.
        Console.WriteLine("Press any key to exit.");
        Console.ReadKey();
    } 
}
/* Output:
    Hello. My name is M and I write lines.
    That's nothing. I'm anonymous and
    I'm a famous author.
    Press any key to exit.
 */

C# 언어 사양

자세한 내용은 C# 언어 사양에서 다음 단원을 참조하십시오.

  • 5.3.3.29 익명 함수

참고 항목

개념

식 트리

참조

문, 식, 연산자(C# 프로그래밍 가이드)

대리자(C# 프로그래밍 가이드)