下面两段代码有什么区别:
using (Object o = new Object())
{
// Do something
}
和
{
Object o = new Object();
// Do something
}
我已经开始更多地使用using
,但我很好奇与作用域对象相比,实际好处是什么。
编辑:我从中得到的有用花絮:
乔恩双向飞碟:
Note that this does not force garbage collection in any way, shape or form. Garbage collection and prompt resource clean-up are somewhat orthogonal.
Will Eddins 评论:
Unless your class implements the IDisposable interface, and has a Dispose() function, you don't use using.
最佳答案
第一个片段在 block 的末尾调用 Dispose
- 你只能用实现 IDisposable
的类型来做,它基本上调用 Dispose
在 finally block 中,因此您可以将它用于需要清理资源的类型,例如
using (TextReader reader = File.OpenText("test.txt"))
{
// Use reader to read the file
}
// reader will be disposed, so file handle released
请注意,这不会强制以任何方式、形状或形式进行垃圾回收。垃圾收集和及时的资源清理在某种程度上是正交的。
基本上,对于几乎所有实现了 IDisposable
并且您的代码块将负责(在清理方面)的任何事情,您都应该使用 using
语句。
关于c# - 'using' 和范围界定之间的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1650800/