C#.NET 使用块
我想在我的 DAL 层中使用“using”块。就像
using (SqlConnection con = new SqlConnection("connection string"))
{
Command object
Reader object
}
由于 SqlConnection 对象在 using 块中初始化一样,我知道当控件退出 using 块作用域时,该连接对象将被自动释放。
但我正在 using 块内创建 Command 和 Reader 对象。我是否必须显式关闭它们,或者我是否必须为它们编写另一个“使用”块。
I want to use the "using" block in my DAL layer. Like
using (SqlConnection con = new SqlConnection("connection string"))
{
Command object
Reader object
}
Since the SqlConnection object in initialised in the using block i know that this connection object will be automatically disposed when the control exits the using block scope.
But i am creating Command and Reader objects inside the using block. Do i have to explicitly close them or do i have to write another "using" block for them.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您还应该对命令和读取器使用
using
,或者显式关闭它们。我通常这样编码:
这限制了标识的数量。
You should use
using
for the Command and Reader as well, or explicitly close them.I normally code it like this:
This limits the number of identations.
您通常也为这些编写 using-blocks,即。
You typically write using-blocks for those as well, ie.
为任何支持 IDisposable 接口的代码编写一个 using 块是值得的。通过这种方式,您可以确保已尽力释放稀缺资源。
It's worth writing a using block for any code that supports IDisposable interface. This way you ensure that you have done what you can to release any scarce resources.
您可以为任何实现
IDispose
的项目创建using
块。因此,您可以在连接块内为每个块创建嵌套的using
块,以确保它们在使用后得到正确处理。You can make
using
blocks for any item that implementsIDispose
. So you can make nestedusing
blocks for each of these, within the block for the connection, to ensure that they are properly disposed of after use.如果您不喜欢使用您的连接和读者,您应该使用
using()
或finally
块。对于读者来说,只有在读者关闭后,连接才会关闭。我还读到using()
并不能 100% 保证连接将被关闭,但我不知道背后的原因,因为它被转换为 try - finally 块并且将在任何情况下都可以执行。You should use
using()
orfinally
blocks if you don't like using for your connections and readers. For readers, connection isn't closed until the reader is closed. Also I've read thatusing()
doesn't 100% guarantee you that the connection will be closed but I don't know the reason behind that since it is converted to try - finally blocks and will be executed in any condition.