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

CHAPTER 15 DELEGATES

Extension of Captured Variable’s Lifetime

A captured outer variable remains alive as long as its capturing method is part of the delegate, even if the variable would have normally gone out of scope.

For example, the code in Figure 15-15 illustrates the extension of a captured variable’s lifetime.

Local variable x is declared and initialized inside a block.

Delegate mDel is then instantiated, using an anonymous method that captures outer variable x.

When the block is closed, x goes out of scope.

If the WriteLine statement following the close of the block were to be uncommented, it would cause a compile error, because it references x, which is now out of scope.

The anonymous method inside delegate mDel, however, maintains x in its environment and prints its value when mDel is invoked.

Figure 15-15. Variable captured in an anonymous method

The code in the figure produces the following output:

Value of x: 5

387

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