Udostępnij za pośrednictwem


Funkcje anonimowe (Przewodnik programowania w języku C#)

Anonimowa funkcja to instrukcja "inline" lub wyrażenie, które mogą być używane wszędzie tam, gdzie oczekuje typem obiektu delegowanego.Można go używać do inicjowania nazwany delegat lub przekazania, to typ delegata nazwany jako parametr metody.

Istnieją dwa rodzaje anonimowe funkcje, które są omawiane w następujących tematach:

Ewolucja delegatów w C#

W C# 1.0 utworzono wystąpienie delegata inicjalizując jawnie go za pomocą metody, która została zdefiniowana w innym miejscu w kodzie.C# 2.0 wprowadzono pojęcie metody anonimowe sposobem napisania nienazwane inline instrukcja bloków, które mogą być wykonywane w wywołania delegata.C# 3.0 wprowadzono wyrażenia lambda, które są podobne do metod anonimowych, ale bardziej wyraziste i zwięzły.Te dwie funkcje są określane zbiorczo jako anonimowych funkcji.Ogólnie rzecz biorąc, aplikacje, przeznaczone w wersji 3.5 lub nowszej z .NET Framework należy użyć wyrażenia lambda.

Poniższy przykład ilustruje ewolucję tworzenia delegata z C# w wersji 1.0 do 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.
 */

Specyfikacja języka C#

Aby uzyskać więcej informacji, zobacz Specyfikacja języka C#. Specyfikacja języka jest ostatecznym źródłem informacji o składni i użyciu języka C#.

Zobacz też

Informacje

Instrukcje, wyrażenia i operatory (Przewodnik programowania w języku C#)

Wyrażenia lambda (Przewodnik programowania w języku C#)

Delegaty (Przewodnik programowania w języku C#)

Koncepcje

Drzewa wyrażeń (C# i Visual Basic)