匿名函式 (C# 程式設計手冊)Anonymous Functions (C# Programming Guide)

匿名函式是可用於任何需要委派類型之處的「內嵌」陳述式或運算式。An anonymous function is an "inline" statement or expression that can be used wherever a delegate type is expected. 您可以使用它來初始化具名委派,或改將它傳遞給具名委派類型作為方法參數。You can use it to initialize a named delegate or pass it instead of a named delegate type as a method parameter.

有兩種類型的匿名函式,將在下列主題中個別進行討論︰There are two kinds of anonymous functions, which are discussed individually in the following topics:

C# 中的委派演進The Evolution of Delegates in C#

在 C# 1.0 中,您已使用該程式碼中其他地方所定義的方法明確初始化委派,來建立委派執行個體。In C# 1.0, you created an instance of a delegate by explicitly initializing it with a method that was defined elsewhere in the code. C# 2.0 引進匿名方法概念,用來撰寫可在委派引動過程中執行的未命名內嵌陳述式區塊。C# 2.0 introduced the concept of anonymous methods as a way to write unnamed inline statement blocks that can be executed in a delegate invocation. C# 3.0 引進 Lambda 運算式,這在概念上與匿名方法類似,但更易懂且更簡潔。C# 3.0 introduced lambda expressions, which are similar in concept to anonymous methods but more expressive and concise. 這兩個功能統稱為「匿名函式」。These two features are known collectively as anonymous functions. 一般而言,以 .NET Framework 3.5 版和更新版本為目標的應用程式應該使用 Lambda 運算式。In general, applications that target version 3.5 and later of the .NET Framework should use lambda expressions.

下列範例示範從 C# 1.0 到 C# 3.0 的委派建立演進:The following example demonstrates the evolution of delegate creation from C# 1.0 to 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# Language Specification

如需詳細資訊,請參閱<C# 語言規格>。For more information, see the C# Language Specification. 語言規格是 C# 語法及用法的限定來源。The language specification is the definitive source for C# syntax and usage.

另請參閱See also