匿名函式 (C# 程式設計手冊)

匿名函式是指可以在任何需要委派型別 (Delegate Type) 的位置上使用的「內嵌」(Inline) 陳述式 (Statement) 或運算式。 您可以用這種函式來初始化具名的委派,或是用它取代具名委派型別來傳遞做為方法參數。

匿名函式可分為兩種,我們將在下列主題中個別加以討論:

C# 中的委派演進

過去在 C# 1.0 中,建立委派之執行個體的步驟,是使用已定義於程式碼內其他位置的方法來明確初始化該委派。 到了 C# 2.0,則引進以匿名方法來撰寫未命名內嵌陳述式區塊的概念,當時,該類區塊會透過委派引動過程來執行。 C# 3.0 引進了 Lambda 運算式,這種運算式與匿名方法的概念相似,但其表示功能更為強大,而且也更簡潔。 這兩種功能合稱為「匿名函式」(Anonymous Function)。 一般而言,以 .NET Framework 3.5 版 (含) 以後版本做為目標的應用程式,都應該使用 Lambda 運算式。

下列範例會示範從 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# 語言規格。語言規格是 C# 語法和用法的限定來源。

請參閱

參考

陳述式、運算式和運算子 (C# 程式設計手冊)

Lambda 運算式 (C# 程式設計手冊)

委派 (C# 程式設計手冊)

概念

運算式樹狀架構 (C# 和 Visual Basic)