是更好地使用[使用]语句在C#或[处理]的方法?这是否适用于外部(COM)对象? [英] Is it better to use the [using] statement in C# or the [dispose] method? Does this apply to external (COM) objects?
问题描述
当一个对象完成了什么是好,使用指令,或者处置指令?
What is better, the using directive, or the dispose directive when finished with an object?
using(FileStream fileStream = new FileStream(
"logs/myapp.log",
FileMode.Open,
FileAccess.Read,
FileShare.ReadWrite))
{
using(StreamReader streamReader = new StreamReader(fileStream))
{
this.textBoxLogs.Text = streamReader.ReadToEnd();
}
}
在另一方面,当我处理System.Net.Mail,有人告诉我,我需要的对象,以Dispose()方法来释放任何杂散锁。
On the other hand, when I'm dealing with System.Net.Mail, I'm told I need to Dispose() of the object to release any stray locks.
有没有一致的指导?我怎么知道什么是更适合于给定对象的给定的情况?
Is there any consistent guidance? How do I tell what is more appropriate in a given situation for a given object?
推荐答案
有没有原因,我能想到的手动调用的Dispose()
,比另一种实现其他对的Dispose()
(例如,在一类,你已经创建了一个工具的IDisposable
)时,你可以用一个对象在使用
块。在使用块使对象的创建和处理在一个try / catch / finally块为 pretty的多 gaurantee该对象将正确处置。
There's no reason that I can think of to manually call Dispose()
, other than in another implementation of Dispose()
(for example in a class you've created that implements IDisposable
) when you can wrap an object in a using
block. The using block puts the creation and disposal of the object in a try/catch/finally block to pretty much gaurantee that the object will be disposed of correctly.
的编译器是比我更可靠。或者你。 =)
MSDN文档的 using语句并呼叫在那里你可以得到在 C#语言规范在这里你可以查看第8.13节using语句 (至少在V4.0中引用它的8.13),让using语句的COM prehensive解释和如何使用它。第五段给出了以下内容:
MSDN documents the using statement and calls out where you can obtain the C# language specification where you can review section 8.13 "The using statement" (at least in the v4.0 reference it's 8.13) that gives a comprehensive explanation of the using statement and how to use it. The fifth paragraph gives the following:
using语句被翻译成 三个部分:获取,使用和 处置。资源的用法 隐式的try语句 它包括一个finally从句。本 最后条款处置的 资源。如果空资源 收购了,那么没有调用Dispose是 制成,并且不会引发任何异常。
A using statement is translated into three parts: acquisition, usage, and disposal. Usage of the resource is implicitly enclosed in a try statement that includes a finally clause. This finally clause disposes of the resource. If a null resource is acquired, then no call to Dispose is made, and no exception is thrown.
这篇关于是更好地使用[使用]语句在C#或[处理]的方法?这是否适用于外部(COM)对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!