表达式树练习实践:C#判断语句

内容纲要

表达式树练习实践:C#判断语句

[TOC]

判断语句

C# 提供了以下类型的判断语句:

语句 描述
if 一个 if 语句 由一个布尔表达式后跟一个或多个语句组成。
if…else 一个 if 语句 后可跟一个可选的 else 语句,else 语句在布尔表达式为假时执行。
嵌套 if 语句 您可以在一个 ifelse if 语句内使用另一个 ifelse if 语句。
switch 语句 一个 switch 语句允许测试一个变量等于多个值时的情况。
嵌套 switch 语 您可以在一个 switch 语句内使用另一个 switch 语句。

当然还有 ???: 等判断,下面将详细实践。

if

If 语句,使用 IfThen(Expression test, Expression ifTrue); 来表达

Expression test表示用于判断的表达式,Expression ifTrue表示结果为 true 时执行的表达式树。

示例

            int a = 10;
            int b = 10;

            if (a == b)
            {
                Console.WriteLine("a == b 为 true,语句被执行");
            }

            Console.ReadKey();

使用表达式树实现如下

            ParameterExpression a = Expression.Variable(typeof(int), "a");
            ParameterExpression b = Expression.Variable(typeof(int), "b");
            MethodCallExpression call = Expression.Call(
                null,
                typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) }),
                Expression.Constant("a == b 为 true,表达式树被执行"));

            ConditionalExpression _if = Expression.IfThen(Expression.Equal(a, b),call);

            Expression<Action<int, int>> lambda = Expression.Lambda<Action<int, int>>(_if,a,b);
            lambda.Compile()(10,10);

            Console.ReadKey();

生成的表达式树如下

.Lambda #Lambda1<System.Action`2[System.Int32,System.Int32]>(
    System.Int32 $a,
    System.Int32 $b) {
    .If ($a == $b) {
        .Call System.Console.WriteLine("a == b 为 true,表达式树被执行")
    } .Else {
        .Default(System.Void)
    }
}

if…else

if…else 使用以下表达式树表示

 ConditionalExpression IfThenElse(Expression test, Expression ifTrue, Expression ifFalse);

示例代码如下

            int a = 10;
            int b = 11;

            if (a == b)
            {
                Console.WriteLine("a == b 为 true,此语句被执行");
            }
            else
            {
                Console.WriteLine("a == b 为 false,此语句被执行");
            }
            Console.ReadKey();

用表达式树实现如下

            ParameterExpression a = Expression.Variable(typeof(int), "a");
            ParameterExpression b = Expression.Variable(typeof(int), "b");
            MethodCallExpression call1 = Expression.Call(
                null,
                typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) }),
                Expression.Constant("a == b 为 true,此表达式树被执行"));

            MethodCallExpression call2 = Expression.Call(
                null,
                typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) }),
                Expression.Constant("a == b 为 false,此表达式树被执行"));

            ConditionalExpression _if = Expression.IfThenElse(Expression.Equal(a, b), call1,call2);

            Expression<Action<int, int>> lambda = Expression.Lambda<Action<int, int>>(_if, a, b);
            lambda.Compile()(10, 11);

            Console.ReadKey();

生成的表达式树如下

.Lambda #Lambda1<System.Action`2[System.Int32,System.Int32]>(
    System.Int32 $a,
    System.Int32 $b) {
    .If ($a == $b) {
        .Call System.Console.WriteLine("a == b 为 true,此表达式树被执行")
    } .Else {
        .Call System.Console.WriteLine("a == b 为 false,此表达式树被执行")
    }
}

switch

示例代码如下

            int a = 2;
            switch (a)
            {
                case 1:Console.WriteLine("a == 1");break;
                case 2:Console.WriteLine("a == 2");break;
                default:Console.WriteLine("a != 1 && a = 2");
            }

            Console.ReadKey();

每个 case 使用 SwitchCase 类型表示,使用 Expression.SwitchCase 生成 SwitchCase 类型。

Expression.Switch 用来构建一个 switch 表达式树,

Expression.Switch 的重载比较多,常用的是这种形式

SwitchExpression Switch(Expression switchValue, Expression defaultBody, params SwitchCase[] cases);

switchValue 表示传入参数;

defaultBody 表示 default 执行的表达式;

cases 表示多条 case 。

上面代码对应使用表达式树编写如下

            ParameterExpression a = Expression.Parameter(typeof(int), "a");
            MethodCallExpression _default = Expression.Call(
                null,
                typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) }),
                Expression.Constant("a != 1 && a = 2"));

            SwitchCase case1 = Expression.SwitchCase(
                Expression.Call(null,
                typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) }),
                Expression.Constant("a == 1")),
                new ConstantExpression[] { Expression.Constant(1) }
                );

            SwitchCase case2 = Expression.SwitchCase(
                Expression.Call(null,
                typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) }),
                Expression.Constant("a == 2")),
                new ConstantExpression[] { Expression.Constant(2) }
                );

            SwitchExpression _switch = Expression.Switch(a, _default, new SwitchCase[] { case1, case2 });
            Expression<Action<int>> lambda = Expression.Lambda<Action<int>>(_switch, a);
            lambda.Compile()(1);

            Console.ReadKey();

生成的表达式树如下

.Lambda #Lambda1<System.Action`1[System.Int32]>(System.Int32 $a) {
    .Switch ($a) {
    .Case (1):
            .Call System.Console.WriteLine("a == 1")
    .Case (2):
            .Call System.Console.WriteLine("a == 2")
    .Default:
            .Call System.Console.WriteLine("a != 1 && a = 2")
    }
}

很奇怪,没有 break,但是表达式树是正常的,并且运行没问题;

?? 和 ?:

?? 表示空合并运算符,例如 a ?? b,如果 a 不为 null,即返回 a,否则返回 b;

常用定义如下

BinaryExpression Coalesce(Expression left, Expression right)

这里就不再赘述。

?: 是三元运算符,例如 a > b ? a : b 。

常用定义如下

ConditionalExpression Condition(Expression test, Expression ifTrue, Expression ifFalse)

可以参考上面的 if…else 表达式树,这里不再赘述。

点赞
  1. olanzapine cost说道:

    Thanks for the useful information on credit repair on your web-site. The thing I would offer as advice to people will be to give up a mentality they will buy at this moment and pay back later. As being a society most people tend to repeat this for many factors. This includes family vacations, furniture, plus items we really want to have. However, you must separate a person's wants from the needs. When you're working to fix your credit score you really have to make some trade-offs. For example you possibly can shop online to economize or you can click on second hand suppliers instead of highly-priced department stores to get clothing.

  2. I simply wanted to thank you so much once more. I am not sure the things that I would've sorted out without the type of strategies revealed by you over that situation. It truly was an absolute horrifying matter in my opinion, however , spending time with the very specialised style you resolved that made me to leap over gladness. I will be happy for this service and then pray you realize what a great job you happen to be providing teaching people today using your web site. Most likely you have never got to know any of us.

  3. buy cbd oil说道:

    I needed to draft you one little observation so as to say thank you as before for these great knowledge you've documented here. It has been certainly pretty generous of people like you to convey freely exactly what a number of people could possibly have made available as an e book to earn some cash for their own end, even more so considering the fact that you could possibly have done it if you ever decided. The ideas also acted like a fantastic way to comprehend other individuals have similar dreams like my own to grasp good deal more in terms of this issue. I'm sure there are many more fun occasions ahead for individuals that go through your blog post.

  4. Wohh just what I was searching for, appreciate it for posting.

发表评论

邮箱地址不会被公开。 必填项已用*标注

You must enable javascript to see captcha here!