我正在开发需要访问数据库的应用程序。使用 using 语句很好,因为"using" statement is to ensure that the object is always disposed correctly, and it doesn't require explicit code to ensure that this happens.
所以我有点困惑哪里使用“使用”,哪里不使用。
public int route(Route r)
{
try
{
using (SqlConnection con = new SqlConnection(connectionString))
{
using(SqlCommand com = new SqlCommand("",con))
{
using (SqlDataReader sdr = com.ExecuteReader())
{
}
}
}
}
catch (Exception e)
{
}
}
任何时候你创建的对象实现IDisposable
,处置它(有或没有using
语法糖)是个好主意 http://msdn.microsoft.com/en-us/library/system.idisposable.dispose(v=vs.110).aspx#remarksToggle.
的好处using
块语法糖(超过手动.Dispose()
调用)是Dispose()
will 仍被称为 https://stackoverflow.com/questions/518352/does-dispose-still-get-called-when-exception-is-thrown-inside-of-a-using-stateme即使出现异常并且流程离开 using 块。
另请注意,您可以堆叠使用,而无需嵌套缩进:
using (SqlConnection con = new SqlConnection(connectionString))
using (SqlCommand com = new SqlCommand("",con))
using (SqlDataReader sdr = com.ExecuteReader()) // Still need to open connection ...
{
...
顺便说一句,还有一个好处using
是如果IDisposable
变量是在using
,即变量is readonly并且不能在块内重新分配 https://msdn.microsoft.com/en-us/library/yh598w02.aspx, e.g.:
using (SqlDataReader sdr = com.ExecuteReader())
{
sdr = new SqlDataReader() // Error
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)