Студопедия — The yield statement
Студопедия Главная Случайная страница Обратная связь

Разделы: Автомобили Астрономия Биология География Дом и сад Другие языки Другое Информатика История Культура Литература Логика Математика Медицина Металлургия Механика Образование Охрана труда Педагогика Политика Право Психология Религия Риторика Социология Спорт Строительство Технология Туризм Физика Философия Финансы Химия Черчение Экология Экономика Электроника

The yield statement






The yield statement is used in an iterator block (§8.2) to yield a value to the enumerator object (§10.14.4) or enumerable object (§10.14.5) of an iterator or to signal the end of the iteration.

yield-statement:
yield return expression;
yield break;

yield is not a reserved word; it has special meaning only when used immediately before a return or break keyword. In other contexts, yield can be used as an identifier.

There are several restrictions on where a yield statement can appear, as described in the following.

· It is a compile-time error for a yield statement (of either form) to appear outside a method-body, operator-body or accessor-body

· It is a compile-time error for a yield statement (of either form) to appear inside an anonymous function.

· It is a compile-time error for a yield statement (of either form) to appear in the finally clause of a try statement.

· It is a compile-time error for a yield return statement to appear anywhere in a try statement that contains any catch clauses.

The following example shows some valid and invalid uses of yield statements.

delegate IEnumerable<int> D();

IEnumerator<int> GetEnumerator() {
try {
yield return 1; // Ok
yield break; // Ok
}
finally {
yield return 2; // Error, yield in finally
yield break; // Error, yield in finally
}

try {
yield return 3; // Error, yield return in try...catch
yield break; // Ok
}
catch {
yield return 4; // Error, yield return in try...catch
yield break; // Ok
}

D d = delegate {
yield return 5; // Error, yield in an anonymous function
};
}

int MyMethod() {
yield return 1; // Error, wrong return type for an iterator block
}

An implicit conversion (§6.1) must exist from the type of the expression in the yield return statement to the yield type (§10.14.3) of the iterator.

A yield return statement is executed as follows:

· The expression given in the statement is evaluated, implicitly converted to the yield type, and assigned to the Current property of the enumerator object.

· Execution of the iterator block is suspended. If the yield return statement is within one or more try blocks, the associated finally blocks are not executed at this time.

· The MoveNext method of the enumerator object returns true to its caller, indicating that the enumerator object successfully advanced to the next item.

The next call to the enumerator object’s MoveNext method resumes execution of the iterator block from where it was last suspended.

A yield break statement is executed as follows:

· If the yield break statement is enclosed by one or more try blocks with associated finally blocks, control is initially transferred to the finally block of the innermost try statement. When and if control reaches the end point of a finally block, control is transferred to the finally block of the next enclosing try statement. This process is repeated until the finally blocks of all enclosing try statements have been executed.

· Control is returned to the caller of the iterator block. This is either the MoveNext method or Dispose method of the enumerator object.

Because a yield break statement unconditionally transfers control elsewhere, the end point of a yield break statement is never reachable.







Дата добавления: 2015-09-07; просмотров: 462. Нарушение авторских прав; Мы поможем в написании вашей работы!



Шрифт зодчего Шрифт зодчего состоит из прописных (заглавных), строчных букв и цифр...

Картограммы и картодиаграммы Картограммы и картодиаграммы применяются для изображения географической характеристики изучаемых явлений...

Практические расчеты на срез и смятие При изучении темы обратите внимание на основные расчетные предпосылки и условности расчета...

Функция спроса населения на данный товар Функция спроса населения на данный товар: Qd=7-Р. Функция предложения: Qs= -5+2Р,где...

Сосудистый шов (ручной Карреля, механический шов). Операции при ранениях крупных сосудов 1912 г., Каррель – впервые предложил методику сосудистого шва. Сосудистый шов применяется для восстановления магистрального кровотока при лечении...

Трамадол (Маброн, Плазадол, Трамал, Трамалин) Групповая принадлежность · Наркотический анальгетик со смешанным механизмом действия, агонист опиоидных рецепторов...

Мелоксикам (Мовалис) Групповая принадлежность · Нестероидное противовоспалительное средство, преимущественно селективный обратимый ингибитор циклооксигеназы (ЦОГ-2)...

ПУНКЦИЯ И КАТЕТЕРИЗАЦИЯ ПОДКЛЮЧИЧНОЙ ВЕНЫ   Пункцию и катетеризацию подключичной вены обычно производит хирург или анестезиолог, иногда — специально обученный терапевт...

Ситуация 26. ПРОВЕРЕНО МИНЗДРАВОМ   Станислав Свердлов закончил российско-американский факультет менеджмента Томского государственного университета...

Различия в философии античности, средневековья и Возрождения ♦Венцом античной философии было: Единое Благо, Мировой Ум, Мировая Душа, Космос...

Studopedia.info - Студопедия - 2014-2024 год . (0.008 сек.) русская версия | украинская версия