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

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

Anonymous function expressions






An anonymous function is an expression that represents an “in-line” method definition. An anonymous function does not have a value or type in and of itself, but is convertible to a compatible delegate or expression tree type. The evaluation of an anonymous function conversion depends on the target type of the conversion: If it is a delegate type, the conversion evaluates to a delegate value referencing the method which the anonymous function defines. If it is an expression tree type, the conversion evaluates to an expression tree which represents the structure of the method as an object structure.

For historical reasons there are two syntactic flavors of anonymous functions, namely lambda-expressions and anonymous-method-expressions. For almost all purposes, lambda-expressions are more concise and expressive than anonymous-method-expressions, which remain in the language for backwards compatibility.

lambda-expression:
asyncopt anonymous-function-signature => anonymous-function-body

anonymous-method-expression:
asyncopt delegate explicit-anonymous-function-signatureopt block

anonymous-function-signature:
explicit-anonymous-function-signature
implicit-anonymous-function-signature

explicit-anonymous-function-signature:
(explicit-anonymous-function-parameter-listopt)

explicit-anonymous-function-parameter-list:
explicit-anonymous-function-parameter
explicit-anonymous-function-parameter-list, explicit-anonymous-function-parameter

explicit-anonymous-function-parameter:
anonymous-function-parameter-modifieropt type identifier

anonymous-function-parameter-modifier:
ref
out

implicit-anonymous-function-signature:
(implicit-anonymous-function-parameter-listopt)
implicit-anonymous-function-parameter

implicit-anonymous-function-parameter-list:
implicit-anonymous-function-parameter
implicit-anonymous-function-parameter-list, implicit-anonymous-function-parameter

implicit-anonymous-function-parameter:
identifier

anonymous-function-body:
expression
block

The => operator has the same precedence as assignment (=) and is right-associative.

An anonymous function with the async modifier is an async function and follows the rules described in §10.14.

The parameters of an anonymous function in the form of a lambda-expression can be explicitly or implicitly typed. In an explicitly typed parameter list, the type of each parameter is explicitly stated. In an implicitly typed parameter list, the types of the parameters are inferred from the context in which the anonymous function occurs—specifically, when the anonymous function is converted to a compatible delegate type or expression tree type, that type provides the parameter types (§6.5).

In an anonymous function with a single, implicitly typed parameter, the parentheses may be omitted from the parameter list. In other words, an anonymous function of the form

(param) => expr

can be abbreviated to

param => expr

The parameter list of an anonymous function in the form of an anonymous-method-expression is optional. If given, the parameters must be explicitly typed. If not, the anonymous function is convertible to a delegate with any parameter list not containing out parameters.

A block body of an anonymous function is reachable (§8.1) unless the anonymous function occurs inside an unreachable statement.

Some examples of anonymous functions follow below:

x => x + 1 // Implicitly typed, expression body

x => { return x + 1; } // Implicitly typed, statement body

(int x) => x + 1 // Explicitly typed, expression body

(int x) => { return x + 1; } // Explicitly typed, statement body

(x, y) => x * y // Multiple parameters

() => Console.WriteLine() // No parameters

async (t1,t2) => await t1 + await t2 // Async

delegate (int x) { return x + 1; } // Anonymous method expression

delegate { return 1 + 1; } // Parameter list omitted

The behavior of lambda-expressions and anonymous-method-expressions is the same except for the following points:

· anonymous-method-expressions permit the parameter list to be omitted entirely, yielding convertibility to delegate types of any list of value parameters.

· lambda-expressions permit parameter types to be omitted and inferred whereas anonymous-method-expressions require parameter types to be explicitly stated.

· The body of a lambda-expression can be an expression or a statement block whereas the body of an anonymous-method-expression must be a statement block.

· Only lambda-expressions have conversions to compatible expression tree types (§4.6).







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



Вычисление основной дактилоскопической формулы Вычислением основной дактоформулы обычно занимается следователь. Для этого все десять пальцев разбиваются на пять пар...

Расчетные и графические задания Равновесный объем - это объем, определяемый равенством спроса и предложения...

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

Обзор компонентов Multisim Компоненты – это основа любой схемы, это все элементы, из которых она состоит. Multisim оперирует с двумя категориями...

Измерение следующих дефектов: ползун, выщербина, неравномерный прокат, равномерный прокат, кольцевая выработка, откол обода колеса, тонкий гребень, протёртость средней части оси Величину проката определяют с помощью вертикального движка 2 сухаря 3 шаблона 1 по кругу катания...

Неисправности автосцепки, с которыми запрещается постановка вагонов в поезд. Причины саморасцепов ЗАПРЕЩАЕТСЯ: постановка в поезда и следование в них вагонов, у которых автосцепное устройство имеет хотя бы одну из следующих неисправностей: - трещину в корпусе автосцепки, излом деталей механизма...

Понятие метода в психологии. Классификация методов психологии и их характеристика Метод – это путь, способ познания, посредством которого познается предмет науки (С...

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

Механизм действия гормонов а) Цитозольный механизм действия гормонов. По цитозольному механизму действуют гормоны 1 группы...

Алгоритм выполнения манипуляции Приемы наружного акушерского исследования. Приемы Леопольда – Левицкого. Цель...

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