“使用”到底有什么用? C# 中的块?
using block
的意义是什么?为什么我应该在 using 块中编写代码?
例如:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["newConnectionString"].ConnectionString);
using (con)
{
con.Open();
//
// Some code
//
con.Close();
}
这是使用 using 语句
的正确方法吗?
Possible Duplicate:
What is the C# Using block and why should I use it?
Whats the significance of using block
? Why should i write my code inside using block?
eg:
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["newConnectionString"].ConnectionString);
using (con)
{
con.Open();
//
// Some code
//
con.Close();
}
Is this the right way of using using statement
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
using
与IDisposable
接口配合使用。它保证在退出作用域之前,将在 using 子句中对对象调用
Dispose
方法。除此之外,没有其他原因。
using
goes together with theIDisposable
interface.It guarantees that before exiting the scope the
Dispose
method would be called on the object in the using clause.There is no other reason than that.
using (x) {...}
只不过是语法糖为了using (x) {...}
is nothing but syntactic sugar for定义是:“定义一个范围,在该范围之外将处理一个或多个对象。”
有关详细信息,请参阅 MSDN。
The definition is: "Defines a scope, outside of which an object or objects will be disposed."
More information can be found in the MSDN.
更多信息请点击这里:
http://www.codeproject.com/KB/cs/tinguusingstatement.aspx
More info here:
http://www.codeproject.com/KB/cs/tinguusingstatement.aspx
using 语句可确保即使在调用对象方法时发生异常,也会调用 Dispose(IDisposable)。在您的示例中,SqlConnection 将在 using 块的末尾关闭并处置。
您的示例不是定义 using 块的常用方法,因为您可能会在 using 块之后意外地重用 con。
试试这个:
The using statement ensures that Dispose (of IDisposable) is called even if an exception occurs while you are calling methods on the object. In your example the SqlConnection will be closed and disposed at the end of the using block.
Your example is not the common way of defining a using block, because you could accidentally reuse con after the using block.
Try this: