C#使用语句的重点是什么?
我不是在谈论对组件的引用,而是代码中的使用语句。
例如,这有什么区别:
using (DataReader dr = .... )
{
...stuff involving data reader...
}
这是什么:
{
DataReader dr = ...
...stuff involving data reader...
}
当垃圾收集器出现时,数据标准肯定会被垃圾收集器清除吗?
I'm not talking about references to assemblies, rather the using statement within the code.
For example what is the difference between this:
using (DataReader dr = .... )
{
...stuff involving data reader...
}
and this:
{
DataReader dr = ...
...stuff involving data reader...
}
Surely the DataReader is cleaned up by the garbage collector when it goes out of scope anyway?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用语句的A
的点是,您使用该语句创建的对象隐含在块末尾处置。在您的第二个代码段中,数据读取器永远不会关闭。这是一种确保不再将一次性资源保留在要求的方法,即使抛出了例外,也将被释放。这是:
在功能上等效:
您可以使用相同的范围对多个可一次性对象这样的范围:
如果您需要交织其他代码,例如
The point of a
using
statement is that the object you create with the statement is implicitly disposed at the end of the block. In your second code snippet, the data reader never gets closed. It's a way to ensure that disposable resources are not held onto any longer than required and will be released even if an exception is thrown. This:is functionally equivalent to this:
You can use the same scope for multiple disposable objects like so:
You only need to nest
using
blocks if you need to interleave other code, e.g.使用语句的此类
自动处理在范围末尾获得的对象。
您可以参考此文档细节。
Such
using
statement automatically disposes the object obtained at the end of scope.You may refer to this documentation for further details.