使用 {} 语句在内部调用 return 是一种好方法吗? [英] Is it a good approach to call return inside using {} statement?

查看:20
本文介绍了使用 {} 语句在内部调用 return 是一种好方法吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只想知道在 using 块内调用 return 是否安全/好方法.

I just want to know is it safe/ good approach to call return inside a using block.

例如

using(var scope = new TransactionScope())
{
  // my core logic
  return true; // if condition met else
  return false;
  scope.Complete();
}

我们知道最后一个大括号 dispose() 将被取消.但是在上述情况下会发生什么,因为 return 将控件跳出给定范围(AFAIK)...

We know the at the last most curly brace dispose() will get called off. But what will be in the above case, since return jumps the control out of the given scope (AFAIK)...

  1. 我的 scope.Complete() 被调用了吗?
  2. 作用域的 dispose() 方法也是如此.
  1. Is my scope.Complete() get called?
  2. And so for the scope's dispose() method.

推荐答案

using 块中调用 return 是完全安全的,因为 using 块只是一个 try/finally 块.

It's perfectly safe to call return inside your using block, since a using block is just a try/finally block.

在上面的示例中,在返回 true 之后,范围将被释放并返回值.return falsescope.Complete()不会被调用.然而,Dispose 将被调用,因为它位于 finally 块中.

In your example above after return true, the scope will get disposed and the value returned. return false, and scope.Complete() will not get called. Dispose however will be called regardless since it reside inside the finally block.

您的代码与此基本相同(如果这样更容易理解的话):

Your code is essentially the same as this (if that makes it easier to understand):

var scope = new TransactionScope())
try
{
  // my core logic
  return true; // if condition met else
  return false;
  scope.Complete();
}
finally
{
  if( scope != null) 
    ((IDisposable)scope).Dispose();
}

请注意,您的事务将从不提交,因为无法通过 scope.Complete() 提交事务.

Please be aware that your transaction will never commit as there's no way to get to scope.Complete() to commit the transaction.

这篇关于使用 {} 语句在内部调用 return 是一种好方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆