首页 > 其他 > 详细

try-catch-finally

时间:2014-10-08 11:13:55      阅读:235      评论:0      收藏:0      [点我收藏+]

通过中间代码窥探try-catch-finally本质:

class Program
    {
        static void Main(string[] args)
        {
            Program p = new Program();
            Console.WriteLine(p.Test1());
            //Console.WriteLine(p.Test2());
            Console.Read();
        }

        //结果为:3
        private TestClass Test1()
        {
            TestClass tc = new TestClass();
            try
            {
                tc.testVar = 2;
                return tc;
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                tc.testVar = 3;
            }
        }

        //结果为:2
        private int Test2()
        {
            int test = 1;
            try
            {
                test = 2;
                return test;
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                test = 3;
            }
        }

    }

    class TestClass
    {
        public int testVar = 111;

        public override string ToString()
        {
            return testVar.ToString();
        }
    }


调用方法Test1,中间代码赋予本地变量的仅是一个引用,所以finally的操作是有影响的,其中间代码为:

bubuko.com,布布扣


调用方法Test2,try中return时,已经将返回值保存在中间代码的本地变量中,而不再是源码中变量test,所以finally的操作是无效的。其中间代码为:

bubuko.com,布布扣

try-catch-finally

原文:http://blog.csdn.net/mzbxzhdxmyb/article/details/39889723

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!