Язык

BlockExpression Класс

Определение

Представляет блок, содержащий последовательность выражений, где можно определить переменные.

public ref class BlockExpression : System::Linq::Expressions::Expression
public class BlockExpression : System.Linq.Expressions.Expression
type BlockExpression = class
    inherit Expression
Public Class BlockExpression
Inherits Expression
Наследование
BlockExpression

Примеры

В следующем примере кода показано, как создать блочное выражение. Выражение блока состоит из двух MethodCallExpression объектов и одного ConstantExpression объекта.

// Add the following directive to your file:
// using System.Linq.Expressions;

// The block expression allows for executing several expressions sequentually.
// When the block expression is executed,
// it returns the value of the last expression in the sequence.
BlockExpression blockExpr = Expression.Block(
    Expression.Call(
        null,
        typeof(Console).GetMethod("Write", new Type[] { typeof(String) }),
        Expression.Constant("Hello ")
       ),
    Expression.Call(
        null,
        typeof(Console).GetMethod("WriteLine", new Type[] { typeof(String) }),
        Expression.Constant("World!")
        ),
    Expression.Constant(42)
);

Console.WriteLine("The result of executing the expression tree:");
// The following statement first creates an expression tree,
// then compiles it, and then executes it.
var result = Expression.Lambda<Func<int>>(blockExpr).Compile()();

// Print out the expressions from the block expression.
Console.WriteLine("The expressions from the block expression:");
foreach (var expr in blockExpr.Expressions)
    Console.WriteLine(expr.ToString());

// Print out the result of the tree execution.
Console.WriteLine("The return value of the block expression:");
Console.WriteLine(result);

// This code example produces the following output:
//
// The result of executing the expression tree:
// Hello World!

// The expressions from the block expression:
// Write("Hello ")
// WriteLine("World!")
// 42

// The return value of the block expression:
// 42
' Add the following directive to your file:
' Imports System.Linq.Expressions

' The block expression enables you to execute several expressions sequentually.
' When the block expression is executed,
' it returns the value of the last expression in the sequence.
Dim blockExpr As BlockExpression = Expression.Block(
    Expression.Call(
        Nothing,
        GetType(Console).GetMethod("Write", New Type() {GetType(String)}),
        Expression.Constant("Hello ")
       ),
    Expression.Call(
        Nothing,
        GetType(Console).GetMethod("WriteLine", New Type() {GetType(String)}),
        Expression.Constant("World!")
        ),
    Expression.Constant(42)
)

Console.WriteLine("The result of executing the expression tree:")
' The following statement first creates an expression tree,
' then compiles it, and then executes it.           
Dim result = Expression.Lambda(Of Func(Of Integer))(blockExpr).Compile()()

' Print the expressions from the block expression.
Console.WriteLine("The expressions from the block expression:")
For Each expr In blockExpr.Expressions
    Console.WriteLine(expr.ToString())
Next

' Print the result of the tree execution.
Console.WriteLine("The return value of the block expression:")
Console.WriteLine(result)

' This code example produces the following output:
'
' The result of executing the expression tree:
' Hello World!

' The expressions from the block expression:
' Write("Hello ")
' WriteLine("World!")
' 42

' The return value of the block expression:
' 42

Комментарии

Методы Block можно использовать для создания BlockExpression.

Свойства

Имя Описание
CanReduce

Указывает, что узел может быть сокращен до более простого узла. Если это возвращает значение true, можно вызвать reduce() для создания сокращенной формы.

(Унаследовано от Expression)
Expressions

Возвращает выражения в этом блоке.

NodeType

Возвращает тип узла этого выражения. Узлы расширения должны возвращаться Extension при переопределении этого метода.

Result

Возвращает последнее выражение в этом блоке.

Type

Возвращает статический тип выражения, представляющего это Expression выражение.

Variables

Возвращает переменные, определенные в этом блоке.

Методы

Имя Описание
Accept(ExpressionVisitor)

Отправляется в конкретный метод посещения для этого типа узла. Например, MethodCallExpression вызывает объект VisitMethodCall(MethodCallExpression).

Equals(Object)

Определяет, равен ли указанный объект текущему объекту.

(Унаследовано от Object)
GetHashCode()

Служит хэш-функцией по умолчанию.

(Унаследовано от Object)
GetType()

Возвращает Type текущего экземпляра.

(Унаследовано от Object)
MemberwiseClone()

Создает неглубокую копию текущей Object.

(Унаследовано от Object)
Reduce()

Сокращает этот узел до более простого выражения. Если CanReduce возвращает значение true, это должно возвращать допустимое выражение. Этот метод может возвращать другой узел, который должен быть сокращен.

(Унаследовано от Expression)
ReduceAndCheck()

Сокращает этот узел до более простого выражения. Если CanReduce возвращает значение true, это должно возвращать допустимое выражение. Этот метод может возвращать другой узел, который должен быть сокращен.

(Унаследовано от Expression)
ReduceExtensions()

Уменьшает выражение до известного типа узла (который не является узлом расширения) или просто возвращает выражение, если оно уже известного типа.

(Унаследовано от Expression)
ToString()

Возвращает текстовое представление Expressionобъекта .

(Унаследовано от Expression)
Update(IEnumerable<ParameterExpression>, IEnumerable<Expression>)

Создает новое выражение, аналогичное этому, но используя предоставленные дочерние элементы. Если все дочерние элементы одинаковы, он вернет это выражение.

VisitChildren(ExpressionVisitor)

Уменьшает узел, а затем вызывает делегат посетителя в сокращенном выражении. Метод создает исключение, если узел не является редуцируемым.

(Унаследовано от Expression)

Применяется к