建议61:避免在finally内撰写无效代码

在阐述建议之前,需要先提出一个问题:是否存在一种打破try-finally执行顺序的情况,答案是:不存在(除非应用程序本身因为某些很少出现的特殊情况在try块中退出)。应该始终认为finally内的代码会在方法return之前执行,哪怕return在try块中。

正是这点,可能会让你写出无效的代码,有时候,这样的无效代码会是一个隐藏很深的Bug。

看下面代码:

        private static int TestIntReturnBelowFinally()
        {
            int i;
            try
            {
                i = 1;
            }
            finally
            {
                i = 2;
                Console.WriteLine("\t将int结果改为2,finally执行完毕");
            }
            return i;
        }

返回值是2。

但是:

        private static int TestIntReturnInTry()
        {
            int i;
            try
            {
                return i = 1;
            }
            finally
            {
                i = 2;
                Console.WriteLine("\t将int结果改为2,finally执行完毕");
            }
        }

返回值是1。

再看下面代码:

        static User TestUserReturnInTry()
        {
            User user = new User() { Name = "Mike", BirthDay = new DateTime(2010, 1, 1) };
            try
            {
                return user;
            }
            finally
            {
                user.Name = "Rose";
                user.BirthDay = new DateTime(2010, 2, 2);
                Console.WriteLine("\t将user.Name改为Rose");
            }
        }

user类:

    class User
    {

        public string Name { get; set; }

        public DateTime BirthDay { get; set; }
    }
View Code

相关文章:

  • 2022-12-23
  • 2021-11-13
  • 2021-12-11
  • 2022-12-23
  • 2022-12-23
  • 2021-07-17
  • 2022-12-23
  • 2021-07-09
猜你喜欢
  • 2021-11-14
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案