C# 表达式树 (16)

2021-02-08  本文已影响0人  wwmin_

系列文章: C# 表达式树及其应用 (Expression 类)

本节继续讲解Expression相关的API, 力争把相关api 都使用简短demo说明一下

    //Throw  创建一个 UnaryExpression,它表示引发异常。
    void ThrowSample()
    {
        TryExpression tryCatchExpr = Expression.TryCatch(
        Expression.Block(
                Expression.Throw(Expression.Constant(new DivideByZeroException())),
                Expression.Constant("Try block")
            ),
            Expression.Catch(
                typeof(DivideByZeroException),
                Expression.Constant("Catch block")
            )
        );
        Expression.Lambda<Func<string>>(tryCatchExpr).Compile()().Dump("throw");
    }
    ThrowSample();

    //ToString   返回 Expression 的的文本化表示形式。见其他ToString
    //TryCatch  创建一个表示 try 块的 TryExpression,该 try 块包含任意数量的 catch 语句,但不包含 fault 和 finally 块。
    void TryCatchSample()
    {
        TryExpression tryCatchExpr = Expression.TryCatch(
            Expression.Block(
                //Expression.Throw(Expression.Constant(new DivideByZeroException())),
                Expression.Throw(Expression.Constant(new ArgumentNullException())),
                Expression.Constant("Try block")
            ),
            Expression.Catch(
                typeof(DivideByZeroException),
                Expression.Constant("Catch block" + typeof(DivideByZeroException))
            ),
            Expression.Catch(
                typeof(ArgumentNullException),
                Expression.Constant("Catch block:" + typeof(ArgumentNullException))
            )
        );
        Expression.Lambda<Func<string>>(tryCatchExpr).Compile()().Dump("TryCatch");//Catch block:System.ArgumentNullException
    }
    TryCatchSample();
    //TryCatchFinally    创建一个表示 try 块的 TryExpression,该 try 块包含任意数量的 catch 语句和一个 finally 块。
    void TryCatchFinallySample()
    {
        TryExpression tryCatchExpr = Expression.TryCatchFinally(
            Expression.Block(
                Expression.Throw(Expression.Constant(new DivideByZeroException())),
                Expression.Constant("Try block")
            ),
            Expression.Call(typeof(Console).GetMethod("WriteLine", new Type[] { typeof(string) })!, Expression.Constant("Finally block")),//Finally block | 
            Expression.Catch(
                typeof(DivideByZeroException),
                Expression.Constant("Catch block")
            )
        );
        Expression.Lambda<Func<string>>(tryCatchExpr).Compile()().Dump("TryCatchFinally");//Catch block
    }
    TryCatchFinallySample();

本文作者:wwmin
微信公众号: DotNet技术说
本文链接:https://www.jianshu.com/p/3fae8f8a5acb
关于博主:评论和私信会在第一时间回复。或者[直接私信]我。
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!
声援博主:如果您觉得文章对您有帮助,关注点赞, 您的鼓励是博主的最大动力!

上一篇 下一篇

猜你喜欢

热点阅读