它是调用里面使用{}语句返回一个好方法? [英] Is it a good approach to call return inside using {} statement?
问题描述
我只是想知道的是它的安全/好方法调用收益
A 使用
块中。
有关前。
使用(VAR范围=新的TransactionScope())
{
//我的核心逻辑
返回真; //如果条件满足别的
返回FALSE;
scope.Complete();
}
我们知道在最后最花括号出售()
将调用关闭。但将在上述情况下的东西,因为收益
跳转控制出给定范围(据我所知)...
的
- 是我的
scope.Complete()
被调用? - 因此对于范围的
的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)...
- Is my
scope.Complete()
get called? - 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屋!