using 语句是否会阻止我关闭或销毁对象?
如果我使用类似的东西:
using (OdbcConnection conn = new OdbcConnection(....))
{
conn.open();
my commands and sql, etc.
}
我必须执行 conn.close(); 吗? 或者 using 语句是否阻止我进行最后一次调用? 它会处理掉 using 块中的所有内容吗? 例如,如果我调用其他不相关的对象,它也会自动处理这些对象吗?
谢谢。 在阅读了微软网站上的使用信息后,我不清楚。 我想确保没有任何内存泄漏。
If I use something like:
using (OdbcConnection conn = new OdbcConnection(....))
{
conn.open();
my commands and sql, etc.
}
Do I have to do a conn.close(); or does the using statement keep me from doing that last call? Does it dispose of everything in the using block? For example, if I called other objects unlrelated would it dipose of those automatically also?
Thank you. I was unclear after reading about using on Microsoft's site. I want to make sure I don't have any memory leaks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
请参阅我的其他答案的顶部 如何在 C# 中使用 using 关键字了解更多信息。
我还应该提到,您可以在完成连接后立即关闭(处置)连接以释放资源。 指南说调用者应该能够重复调用 dispose 方法。 using 块本质上只是一个安全网,允许在大多数情况下编写更清晰的代码。
[编辑]
例如,using 中的多重初始化:在同一个 using 中初始化多个对象,如果对象类型相同,则不必嵌套 using 块:
Joel Coehoorn 提到了堆栈,这是嵌套但省略了大括号,就像您可以省略大括号一样在
for
或if
语句中。 UI 不会通过缩进重新格式化。 我很好奇 IL 是什么样子的。使用 put 不同的对象在同一个 using 中是错误的
错误 CS1044:无法在 for、using、fixed 或声明语句中使用多种类型。
See the top bit of my other answer for How do I use the using keyword in C# for a little more information.
I should also mention that you can close (dispose) of the connection as soon as you are done with it to release the resource. The guidelines say that the caller should be able to repeatedly call the dispose method. The using block is essentially just a safety net and allows writing clearer code in most circumstances.
[Edit]
e.g. multiple initialization in a using: initialize more than one object in the same using without having to nest using blocks if the objects are the same type:
Joel Coehoorn mentioned stacking, which is nesting but omitting the braces, much as you can omit the braces in a
for
, orif
statement. The UI doesn't reformat with an indent. I'd be curious what the IL looks like.It is an error to use put different objects in the same using
error CS1044: Cannot use more than one type in a for, using, fixed, or declaration statement.
using 语句将为您调用 Close 和 Dispose 方法。
Scott Hanselman 对 using 语句有很好的解释。
The using statement will handle calling the Close and Dispose methods for you.
Scott Hanselman has a pretty good explanation of the using statement.
using 语句确保实现 IDisposable 的对象被释放。 它只会处理 using 块中引用的对象,因此您的代码基本上相当于:
The using statement ensures that an object which implements IDisposable gets disposed. It will only dispose the object that is referened in the using block so your code is basically equivlant to: