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

CHAPTER 15 DELEGATES

Anonymous Methods

So far, you’ve seen that you can use either static methods or instance methods to instantiate a delegate. In either case, the method itself can be called explicitly from other parts of the code and, of course, must be a member of some class or struct.

What if, however, the method is used only one time—to instantiate the delegate? In that case, other than the syntactic requirement for creating the delegate, there is no real need for a separate, named method. Anonymous methods allow you to dispense with the separate, named method.

An anonymous method is a method that is declared inline, at the point of instantiating a delegate.

For example, Figure 15-12 shows two versions of the same class. The version on the left declares and uses a method named Add20. The version on the right uses an anonymous method instead. The nonshaded code of both versions is identical.

Figure 15-12. Comparing a named method and an anonymous method

Both sets of code in Figure 15-12 produce the following output:

25

26

Using Anonymous Methods

You can use an anonymous method in the following places:

As an initializer expression when declaring a delegate variable.

On the right side of an assignment statement when combining delegates.

On the right side of an assignment statement adding a delegate to an event. Chapter 16 covers events.

383

CHAPTER 15 DELEGATES

Syntax of Anonymous Methods

The syntax of an anonymous method expression includes the following components:

The type keyword delegate

The parameter list, which can be omitted if the statement block doesn’t use any parameters

The statement block, which contains the code of the anonymous method

 

Parameter

 

 

 

Keyword

list

 

Statement block

 

 

delegate ( Parameters )

{ ImplementationCode }

Return Type

An anonymous method does not explicitly declare a return type. The behavior of the implementation code itself, however, must match the delegate’s return type by returning a value of that type. If the delegate has a return type of void, then the anonymous method code cannot return a value.

For example, in the following code, the delegate’s return type is int. The implementation code of the anonymous method must therefore return an int on all pathways through the code.

Return type of delegate type

delegate int OtherDel(int InParam);

 

static void Main()

 

{

 

OtherDel del = delegate(int x)

 

{

 

return x + 20 ;

// Returns an int

};

 

...

 

}

 

384

CHAPTER 15 DELEGATES

Parameters

Except in the case of array parameters, the parameter list of an anonymous method must match that of the delegate in the following three characteristics:

Number of parameters

Types and positions of the parameters

Modifiers

You can simplify the parameter list of an anonymous method by leaving the parentheses empty or omitting them altogether, but only if both of the following are true:

The delegate’s parameter list does not contain any out parameters.

The anonymous method does not use any parameters.

For example, the following code declares a delegate that does not have any out parameters and an anonymous method that does not use any parameters. Since both conditions are met, you can omit the parameter list from the anonymous method.

delegate void SomeDel ( int X );

// Declare the delegate type.

SomeDel SDel = delegate

// Parameter list omitted

{

 

PrintMessage();

 

Cleanup();

 

};

 

params Parameters

If the delegate declaration’s parameter list contains a params parameter, then the params keyword is omitted from the parameter list of the anonymous method. For example, in the following code, this happens:

The delegate type declaration specifies the last parameter as a params type parameter.

The anonymous method parameter list, however, must omit the params keyword.

params keyword used in delegate type declaration

delegate void SomeDel( int X, params int[] Y);

params keyword omitted in matching anonymous method

SomeDel mDel = delegate (int X, int[] Y)

{

...

};

385

CHAPTER 15 DELEGATES

Scope of Variables and Parameters

The scopes of parameters and local variables declared inside an anonymous method are limited to the body of the implementation code, as illustrated in Figure 15-13.

For example, the following anonymous method defines parameter y and local variable z. After the close of the body of the anonymous method, y and z are no longer in scope. The last line of the code would produce a compile error.

Figure 15-13. Scope of variables and parameters

Outer Variables

Unlike the named methods of a delegate, anonymous methods have access to the local variables and environment of the scope surrounding them.

Variables from the surrounding scope are called outer variables.

An outer variable used in the implementation code of an anonymous method is said to be captured by the method.

For example, the code in Figure 15-14 shows variable x defined outside the anonymous method. The code in the method, however, has access to x and can print its value.

Figure 15-14. Using an outer variable

386

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