问题描述
最近,我已经看到了写了一些代码如下:
Recently I've seen some code written as follows:
public void Dipose()
{
using(_myDisposableField) { }
}
这似乎很奇怪,我,我倒是更愿意看到 myDisposableField.Dispose();
This seems pretty strange to me, I'd prefer to see myDisposableField.Dispose();
使用处置有什么理由存在使用你的对象上明确打出电话?
What reasons are there for using "using" to dispose your objects over explicitly making the call?
推荐答案
删除它。你使代码更快,更具可读性,也许是最重要的(如你继续阅读下面的)更多的的表现在它的意图的
Remove it. You'll make the code faster, more readable, and perhaps most importantly (as you continue reading below) more expressive in its intent.
更新:他们被的略的聪明,相当于代码需要一个空的检查,并按照乔恩斯基特的意见,也需要一个本地副本,如果多穿线参与(以同样的方式作为标准事件调用模式以避免空检查和方法的调用之间的竞争)。
Update: they were being slightly clever, equivalent code needs a null check and as per Jon Skeet's advice, also take a local copy if multi-threading is involved (in the same manner as the standard event invocation pattern to avoid a race between the null check and method call).
IDisposable tmp = _myDisposableField;
if (tmp != null)
tmp.Dispose();
从我可以在我写了一个示例应用程序的IL看,它看起来像你还需要 _myDisposableField
为的IDisposable
直接处理。这将是重要的,如果任何类型实现了的IDisposable
接口明确地和也的提供了一个公开同时无效的Dispose()
方法。
From what I can see in the IL of a sample app I've written, it looks like you also need to treat _myDisposableField
as IDisposable
directly. This will be important if any type implements the IDisposable
interface explicitly and also provides a public void Dispose()
method at the same time.
这代码也不会尝试复制试戴最后
,当使用使用
存在,但它是那种假设,这是认为是不必要的。正如迈克尔Graczyk在评论中指出的,但是在使用的最后
提供保护,防止异常,特别是 ThreadAbortException
(这可能发生在任何点)。尽管如此,窗口这实际发生的是非常小的。
This code also doesn't attempt to replicate the try-finally
that exists when using using
, but it is sort of assumed that this is deemed unnecessary. As Michael Graczyk points out in the comments, however, the use of the finally
offers protection against exceptions, in particular the ThreadAbortException
(which could occur at any point). That said, the window for this to actually happen in is very small.
虽然,我对持股他们这样做不是真正的理解其实是一个五元美钞什么微妙好处,它给了他们。
Although, I'd stake a fiver on the fact they did this not truly understanding what subtle "benefits" it gave them.
这篇关于空"采用"在处置声明的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!