面向云技术架构 - 痴者工良

  • 首页
  • 工良写的电子书
    • kubernetes 教程
    • 从 C# 入门 Kafka
    • 多线程和异步
    • 动态编程-反射、特性、AOP
    • 表达式树
  • 本站文章导航
  • 隐私政策
愿有人陪你颠沛流离
遇到能让你付出的事物或者人,都是一种运气。
能遇到,就该珍惜。或许你们最终没能在一起,但你会切实地感受到力量。
正因为这样,那段相遇才变得有价值,才没有辜负这世间的每一段相遇。
  1. 首页
  2. .NET
  3. 正文

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

2019年12月15日 1918点热度 0人点赞 4条评论
内容纲要

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

[TOC]

判断语句

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

语句 描述
if 一个 if 语句 由一个布尔表达式后跟一个或多个语句组成。
if...else 一个 if 语句 后可跟一个可选的 else 语句,else 语句在布尔表达式为假时执行。
嵌套 if 语句 您可以在一个 if 或 else if 语句内使用另一个 if 或 else 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 表达式树,这里不再赘述。

本作品采用 知识共享署名-非商业性使用-相同方式共享 4.0 国际许可协议 进行许可
标签: c 使用 变量 测试 类型
最后更新:2021年2月21日

痴者工良

高级程序员劝退师

点赞
< 上一篇
下一篇 >

文章评论

razz evil exclaim smile redface biggrin eek confused idea lol mad twisted rolleyes wink cool arrow neutral cry mrgreen drooling persevering
取消回复

文章目录
  • 表达式树练习实践:C#判断语句
    • if
    • if...else
    • switch
    • ?? 和 ?:

COPYRIGHT © 2022 whuanle.cn. ALL RIGHTS RESERVED.

Theme Kratos Made By Seaton Jiang

粤ICP备18051778号

粤公网安备 44030902003257号