它是调用里面使用{}语句返回一个好方法? [英] Is it a good approach to call return inside using {} statement?

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

问题描述

我只是想知道的是它的安全/好方法调用收益 A 使用块中。



有关前。

 使用(VAR范围=新的TransactionScope()) 
{
//我的核心逻辑
返回真; //如果条件满足别的
返回FALSE;
scope.Complete();
}

我们知道在最后最花括号出售()将调用关闭。但将在上述情况下的东西,因为收益跳转控制出给定范围(据我所知)...




  1. 是我的 scope.Complete()被调用?

  2. 因此对于范围的的Dispose()方法。


解决方案

这是完全安全地调用收益里面的使用块,因为使用块只是一个尝试/终于块。



在你上面的例子返回后真正,适用范围将得到处置和返回值。 返回false scope.Complete()不可以被调用。 的Dispose 但是会考虑所谓的,因为它位于内部的finally块。



您的代码基本上是相同的,因为这(如果这使得它更容易理解):

  VAR范围=新的TransactionScope())

{
//我的核心逻辑
返回真; //如果条件满足别的
返回FALSE;
scope.Complete();
}
终于
{
如果
((IDisposable接口)范围).Dispose()(范围!= NULL);
}

请注意,您的交易将绝不会提交因为没有办法去 scope.Complete()来提交事务。


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

For ex.

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

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. Is my scope.Complete() get called?
  2. And so for the scope's dispose() method.

解决方案

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

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();
}

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

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

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