Expression.IfThenElse(Expression, Expression, Expression) 方法
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
建立 ConditionalExpression,代表具有 if
和 else
陳述式的條件區塊。
public:
static System::Linq::Expressions::ConditionalExpression ^ IfThenElse(System::Linq::Expressions::Expression ^ test, System::Linq::Expressions::Expression ^ ifTrue, System::Linq::Expressions::Expression ^ ifFalse);
public static System.Linq.Expressions.ConditionalExpression IfThenElse (System.Linq.Expressions.Expression test, System.Linq.Expressions.Expression ifTrue, System.Linq.Expressions.Expression ifFalse);
static member IfThenElse : System.Linq.Expressions.Expression * System.Linq.Expressions.Expression * System.Linq.Expressions.Expression -> System.Linq.Expressions.ConditionalExpression
Public Shared Function IfThenElse (test As Expression, ifTrue As Expression, ifFalse As Expression) As ConditionalExpression
參數
- test
- Expression
要將 Expression 屬性設定為與之相等的 Test。
- ifTrue
- Expression
要將 Expression 屬性設定為與之相等的 IfTrue。
- ifFalse
- Expression
要將 Expression 屬性設定為與之相等的 IfFalse。
傳回
ConditionalExpression,其 NodeType 屬性等於 Conditional,且 Test、IfTrue 和 IfFalse 屬性設定為指定的值。 這個方法所傳回之結果 ConditionalExpression 的類型為 Void。
範例
下列程式代碼範例示範如何建立代表條件式區塊的表達式。
// Add the following directive to the file:
// using System.Linq.Expressions;
bool test = true;
// This expression represents the conditional block.
Expression ifThenElseExpr = Expression.IfThenElse(
Expression.Constant(test),
Expression.Call(
null,
typeof(Console).GetMethod("WriteLine", new Type[] { typeof(String) }),
Expression.Constant("The condition is true.")
),
Expression.Call(
null,
typeof(Console).GetMethod("WriteLine", new Type[] { typeof(String) }),
Expression.Constant("The condition is false.")
)
);
// The following statement first creates an expression tree,
// then compiles it, and then runs it.
Expression.Lambda<Action>(ifThenElseExpr).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 ifThenElseExpr As Expression = Expression.IfThenElse(
Expression.Constant(test),
Expression.Call(
Nothing,
GetType(Console).GetMethod("WriteLine", New Type() {GetType(String)}),
Expression.Constant("The condition is true.")
),
Expression.Call(
Nothing,
GetType(Console).GetMethod("WriteLine", New Type() {GetType(String)}),
Expression.Constant("The condition is false.")
)
)
' The following statement first creates an expression tree,
' then compiles it, and then runs it.
Expression.Lambda(Of Action)(ifThenElseExpr).Compile()()
' This code example produces the following output:
'
' The condition is true.