logo search
CSharp_Prog_Guide

Выражения вызова

В следующем примере кода вызов метода DoWork является выражением вызова.

DoWork();

При вызове метода необходимо указать имя метода в явном виде, как было показано в предыдущем примере, или в виде результата другого выражения, после чего в скобках указываются все параметры этого метода. Дополнительные сведения см. в разделе Методы. При вызове делегата указывается имя делегата и параметры метода в скобках. Дополнительные сведения см. в разделе Делегаты. Результатом вызова метода или делегата является возвращаемое методом значение, если метод вообще возвращает значение. В качестве значений в выражениях нельзя использовать методы, возвращающие значение типа void.

Query Expressions

The same rules for expressions in general apply to query expressions.

Lambda Expressions

Lambda expressions represent "inline methods" that have no name but can have input parameters and multiple statements. They are used extensively in LINQ to pass arguments to methods. Lambda expressions are compiled to either delegates or expression trees depending on the context in which they are used. For more information, see Lambda Expressions.

Expression Trees

Expression trees enable expressions to be represented as data structures. They are used extensively by LINQ providers to translate query expressions into code that is meaningful in some other context, such as a SQL database.

Remarks

Whenever a variable, object property, or object indexer access is identified from an expression, the value of that item is used as the value of the expression. An expression can be placed anywhere in C# where a value or object is required, as long as the expression ultimately evaluates to the required type.

Выражения запроса21

Аналогичные правила в общем случае относятся и к выражениям запроса.

Лямбда-выражения

Лямбда-выражения представляют собой "встроенные методы", у которых нет имен, но которые могут иметь входные параметры и несколько инструкций. Они активно используются в LINQ для передачи параметров методам. Лямбда-выражения компилируются в делегаты или в деревья выражений в зависимости от условий, при которых они используются. Дополнительные сведения см. в разделе Лямбда-выражения.

Деревья выражений

Деревья выражения позволяют представлять выражения в виде структур данных. Они активно используются поставщиками LINQ для преобразования выражений запросов в код, имеющий смысл в других контекстах, например в базах данных SQL.

Заметки

Если в выражении присутствует переменная, свойство объекта или индексатор объекта, для вычисления выражения используется значение этого элемента. В C# выражение можно использовать везде, где требуется значение или объект, если результат вычисления выражения соответствует требуемому типу.

Operators

In C#, an operator is a term or a symbol that takes one or more expressions, called operands, as input and returns a value. Operators that take one operand, such as the increment operator (++) or new, are called unary operators. Operators that take two operands, such as arithmetic operators (+,-,*,/) are called binary operators. One operator, the conditional operator (?:), takes three operands and is the sole tertiary operator in C#.

The following C# statement contains a single unary operator, and a single operand. The increment operator, ++, modifies the value of the operand y.:

y++;

The following C# statement contains two binary operators, each with two operands. The assignment operator, =, has the integer y, and the expression 2 + 3 as operands. The expression 2 + 3 itself contains the addition operator, and uses the integer values 2 and 3 as operands:

y = 2 + 3;

An operand can be a valid expression of any size, composed of any number of other operations.

Operators in an expression are evaluated in a specific order known as operator precedence. The following table divides the operators into categories based on the type of operation they perform. The categories are listed in order of precedence.

Primary

x.y, f(x), a[x], x++, x--, new, typeof, checked, unchecked

Unary

+, -, !, ~, ++x, --x, (T)x

Arithmetic — Multiplicative

*, /, %

Arithmetic — Additive

+, -

Shift

<<, >>

Relational and type testing

<, >, <=, >=, is, as

Equality

==, !=

Logical, in order of precedence

&, ^, |

Conditional, in order of precedence

&&, ||, ?:

Assignment

=, +=, -=, *=, /=, %=, &=, |=, ^=, <<=, >>=, =>