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.