问题描述
Close()
与 Dispose()
相同还是使用using语句。
Is Close()
same as Dispose()
or using statement. Is it necessary to call using statement even if Close is called?.
我知道在处置对象之前,应先调用close,这样我们就可以关闭资源并可能可用于处置
。
I know before disposing of an object, close should be called, so we close the resource and may it available to Dispose
.
使用
仅适用于 IDisposable
继承的对象,请参见:
using
only applies to IDisposable
inherited objects, see: https://msdn.microsoft.com/en-us/library/yh598w02.aspx
Close()
和 Dispose()
可能没有任何关系。
Close()
and Dispose()
may not considered to be related in any way.
当 IDisposable
接口已正确实现,您可以假设将执行所有必要的清理工作。这意味着将执行对 Close()
方法的内部调用。这意味着不需要显式调用 Close()
。
When the IDisposable
interface is correctly implemented, you may assume all clean-up necessary will be carried out. This implies an internal call to a Close()
method would be carried out. This means that an explicit call to Close()
should not be necessary.
当对象的类型为 IDisposable
并公开 Close()
方法时,将调用 Close()
不足以正确处理/清理对象。必须仍然调用 Dispose()
,您可以直接执行此操作,也可以通过 using
语句来执行此操作。
The other way round; when a object is of type IDisposable
and exposes a Close()
method, a call to Close()
will not be sufficient to properly dispose/clean-up the object. Dispose()
must still be called, you can do this directly, or through the using
statement.
您还可以让垃圾收集器为您处理 Dispose()
调用(如果正确实施,请参阅:),但是这被认为是不好的做法,因为您需要依靠适当的实现并且不能直接控制GC的时间。
You can also let the garbage-collector handle the Dispose()
call for you (if its correctly implemented, see: Proper use of the IDisposable interface) But this is considered bad-practice, since you need to rely on a proper implementation and have no direct control over the GC timing.
请注意,实施关闭的原因()
函数,通常是为开发人员提供一种重用对象的方法。调用 Dispose()
之后,该对象被视为已标记为完成,并且可能不再使用。
Please note, a reason to implement a Close()
function, is usually to give a developer a way to reuse the object. After calling Dispose()
the object is considered to be marked for finalization and may not be used any more.
这篇关于Close()是否与Using语句相同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!