Expression.IfThen(Expression, Expression) 方法

定義

建立 ConditionalExpression,代表具有 if 陳述式的條件區塊。

public:
 static System::Linq::Expressions::ConditionalExpression ^ IfThen(System::Linq::Expressions::Expression ^ test, System::Linq::Expressions::Expression ^ ifTrue);
public static System.Linq.Expressions.ConditionalExpression IfThen (System.Linq.Expressions.Expression test, System.Linq.Expressions.Expression ifTrue);
static member IfThen : System.Linq.Expressions.Expression * System.Linq.Expressions.Expression -> System.Linq.Expressions.ConditionalExpression
Public Shared Function IfThen (test As Expression, ifTrue As Expression) As ConditionalExpression

參數

test
Expression

要將 Expression 屬性設定為與之相等的 Test

ifTrue
Expression

要將 Expression 屬性設定為與之相等的 IfTrue

傳回

ConditionalExpression

ConditionalExpression,其 NodeType 屬性等於 Conditional,且 TestIfTrue 屬性設定為指定的值。 IfFalse 屬性已設定為預設運算式,而這個方法傳回之結果 ConditionalExpression 的類型為 Void

範例

下列程式碼範例示範如何建立代表條件式區塊的運算式。

// Add the following directive to the file:
// using System.Linq.Expressions;
bool test = true;

// This expression represents the conditional block.
Expression ifThenExpr = Expression.IfThen(
    Expression.Constant(test),
    Expression.Call(
        null,
        typeof(Console).GetMethod("WriteLine", new Type[] { typeof(String) }),
        Expression.Constant("The condition is true.")
       )
);

// The following statement first creates an expression tree,
// then compiles it, and then runs it.
Expression.Lambda<Action>(ifThenExpr).Compile()();

// This code example produces the following output:
//
// The condition is true.
' Add the following directive to the file:
' Imports System.Linq.Expressions

Dim test As Boolean = True

' This expression represents the conditional block.
Dim ifThenExpr As Expression = Expression.IfThen(
     Expression.Constant(test),
     Expression.Call(
         Nothing,
         GetType(Console).GetMethod("WriteLine", New Type() {GetType(String)}),
         Expression.Constant("The condition is true.")
     )
)

' The following statement first creates an expression tree,
' then compiles it, and then runs it.
Expression.Lambda(Of Action)(ifThenExpr).Compile()()

' This code example produces the following output:
'
' The condition is true.

適用於