Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Daniel Solis - Illustrated C# 2010 - 2010.pdf
Скачиваний:
16
Добавлен:
11.06.2015
Размер:
11.23 Mб
Скачать

CHAPTER 15 DELEGATES

Lambda Expressions

C# 2.0 introduced anonymous methods, which allowed you to include short bits of inline code when creating or adding to delegates. The syntax for anonymous methods, however, is somewhat verbose and requires information that the compiler itself already knows. Rather than requiring you to include this redundant information, C# 3.0 introduced lambda expressions, which pare down the syntax of anonymous methods. You’ll probably want to use lambda expressions instead of anonymous methods. In fact, if lambda expressions had been introduced first, there never would have been anonymous methods.

In the anonymous method syntax, the delegate keyword is redundant because the compiler can already see that you’re assigning the method to a delegate. You can easily transform an anonymous method into a lambda expression by doing the following:

Delete the delegate keyword.

Place the lambda operator, =>, between the parameter list and the body of the anonymous method. The lambda operator is read as “goes to.”

The following code shows this transformation. The first line shows an anonymous method being assigned to variable del. The second line shows the same anonymous method after having been transformed into a lambda expression, being assigned to variable le1.

MyDel

del

=

delegate(int

x)

{

return

x

+

1;

}

;

//

Anonymous method

MyDel

le1

=

(int

x)

=> {

return

x

+

1;

}

;

//

Lambda expression

Note The term lambda expression comes from the lambda calculus, which was developed in the 1920s and 1930s by mathematician Alonzo Church and others. The lambda calculus is a system for representing functions and uses the Greek letter lambda (λ) to represent a nameless function. More recently, functional programming languages such as Lisp and its dialects use the term to represent expressions that can be used to directly describe the definition of a function, rather than using a name for it.

388

CHAPTER 15 DELEGATES

This simple transformation is less verbose and looks cleaner, but it only saves you six characters. There’s more, however, that the compiler can infer, allowing you to simplify the lambda expression further, as shown in the following code.

From the delegate’s declaration, the compiler also knows the types of the delegate’s parameters, so the lambda expression allows you to leave out the parameter types, as shown in the assignment to le2.

Parameters listed with their types are called explicitly typed.

Those listed without their types are called implicitly typed.

If there’s only a single, implicitly typed parameter, you can leave off the parentheses surrounding it, as shown in the assignment to le3.

Finally, lambda expressions allow the body of the expression to be either a statement block or an expression. If the statement block contains a single return statement, you can replace the statement block with just the expression that follows the return keyword, as shown in the assignment to le4.

MyDel del = delegate(int

x)

 

{ return x + 1; } ;

// Anonymous method

MyDel le1 =

(int

x) => { return x + 1; } ;

// Lambda expression

MyDel le2 =

 

(x) => {

return

x + 1; } ;

// Lambda expression

MyDel

le3

=

 

x

=> {

return

x

+

1; } ;

//

Lambda

expression

MyDel

le4

=

 

x

=>

 

 

x

+

1

;

//

Lambda

expression

The final form of the lambda expression has about one-fourth the characters of the original anonymous method and is cleaner and easier to understand.

389

CHAPTER 15 DELEGATES

The following code shows the full transformation. The first line of Main shows an anonymous method being assigned to variable del. The second line shows the same anonymous method, after having been transformed into a lambda expression, being assigned to variable le1.

delegate double MyDel(int par);

static void Main()

 

 

 

 

 

 

{

 

 

 

 

 

 

MyDel del = delegate(int

x)

{ return x + 1; } ;

// Anonymous method

MyDel le1 =

(int

x) => { return x + 1; } ;

// Lambda expression

MyDel le2 =

 

(x) => { return x + 1; } ;

 

MyDel le3 =

 

x => { return x + 1; } ;

 

MyDel le4 =

 

x

=>

x + 1

;

 

Console.WriteLine("{0}",

del (12));

 

 

 

Console.WriteLine("{0}",

le1 (12));

Console.WriteLine("{0}", le2 (12));

Console.WriteLine("{0}",

le3 (12));

Console.WriteLine("{0}", le4 (12));

}

 

 

 

 

 

 

Some important points about lambda expression parameter lists are the following:

The parameters in the parameter list of a lambda expression must match that of the delegate in number, type, and position.

The parameters in the parameter list of an expression do not have to include the type (that is, implicitly typed) unless the delegate has either ref or out parameters—in which case the types are required (that is, explicitly typed).

If there is only a single parameter and it is implicitly typed, the surrounding parentheses can be omitted. Otherwise, they are required.

If there are no parameters, you must use an empty set of parentheses.

Figure 15-16 shows the syntax for lambda expressions.

Figure 15-16. The syntax for lambda expressions consists of the lambda operator with the parameter section on the left and the lambda body on the right.

390

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]