logo search
CSharp_Prog_Guide

Использование лямбда-выражений вне linq

Лямбда-выражения не ограничиваются запросами LINQ. Их можно использовать везде, где ожидается значение-делегат, то есть везде, где можно использовать анонимные методы. В следующем примере показано, как использовать лямбда-выражение в обработчике событий Windows Forms. Обратите внимание, что входные типы (Object и MouseEventArgs) выводятся компилятором, их не нужно явным образом указывать во входных параметрах лямбда-выражения.

Пример

public partial class Form1 : Form

{

public Form1()

{

InitializeComponent();

// Use a lambda expression to define an event handler.

this.Click += (s, e) => { MessageBox.Show(((MouseEventArgs)e).Location.ToString());};

}

}

Anonymous Methods

In versions of C# before 2.0, the only way to declare a delegate was to use named methods. C# 2.0 introduced anonymous methods and in C# 3.0 and later, lambda expressions supersede anonymous methods as the preferred way to write inline code. However, the information about anonymous methods in this topic also applies to lambda expressions. There is one case in which an anonymous method provides functionality not found in lambda expressions. Anonymous methods enable you to omit the parameter list, and this means that an anonymous method can be converted to delegates with a variety of signatures. This is not possible with lambda expressions. For more information specifically about lambda expressions, see Lambda Expressions.

Creating anonymous methods is essentially a way to pass a code block as a delegate parameter. Here are two examples:

// Create a handler for a click event

button1.Click += delegate(System.Object o, System.EventArgs e)

{ System.Windows.Forms.MessageBox.Show("Click!"); };

// Create a delegate instance

delegate void Del(int x);

// Instantiate the delegate using an anonymous method

Del d = delegate(int k) { /* ... */ };

By using anonymous methods, you reduce the coding overhead in instantiating delegates because you do not have to create a separate method.

For example, specifying a code block instead of a delegate can be useful in a situation when having to create a method might seem an unnecessary overhead. A good example would be when you start a new thread. This class creates a thread and also contains the code that the thread executes without creating an additional method for the delegate.

void StartThread()

{

System.Threading.Thread t1 = new System.Threading.Thread

(delegate()

{

System.Console.Write("Hello, ");

System.Console.WriteLine("World!");

});

t1.Start();

}