Sometimes it's useful to think of Linq expressions as a way to create code in something that resembles C # but is not exactly C #. This is just the case.
The code below is an implementation Math.Max(int a, int b)using expressions. For operators returnlike C #, there is no shortcut. You must create tags.
var a = Expression.Parameter(typeof(int), "a");
var b = Expression.Parameter(typeof(int), "b");
var returnLabel = Expression.Label(typeof (int));
Expression<Func<int, int, int>> returnMax = (Expression<Func<int, int, int>>)Expression.Lambda
(
Expression.Block
(
Expression.IfThenElse
(
Expression.GreaterThan(a, b),
Expression.Return(returnLabel, a),
Expression.Return(returnLabel, b)
),
Expression.Label(returnLabel, Expression.Constant(0))
),
a,
b
);
var shouldBeSix = returnMax.Compile()(5, 6);
, LabelExpression : ( void - ) . A BlockExpression, , . AssignExpression . , a LabelExpression . GotoExpression , :
var returnLabel = Expression.Label(typeof (int));
Expression<Func<int>> returnsSix = (Expression<Func<int>>)Expression.Lambda
(
Expression.Label(
returnLabel,
Expression.Constant(6)
)
);
var alsoSix = returnsSix.Compile()();
... , .
a LabelExpression , LabelTarget GotoExpression. 0 , , , . 0 0.0 null, .Compile().
2) , "" . @Grax, Expression.Goto, Expression.Continue, Expression.Break, Expression.Return GotoExpressions, .