释放或使用关键字"using"



我真的需要使用comm.Dispose()conn.Dispose()还是直接使用using

using (OdbcConnection conn = new OdbcConnection())
{
    conn.Open();
    OdbcCommand comm = new OdbcCommand(sql, conn);
    OdbcDataReader dr = comm.ExecuteReader();
    while (dr.Read())
    {
      //codes here...
    }
    conn.Close();
    dr.Close();
    comm.Dispose();
    conn.Dispose();
}

如果是这样的话,我正在考虑这样做。

片段:

using (OdbcConnection conn = new OdbcConnection())
{
    conn.Open();
    using(OdbcCommand comm = new OdbcCommand(sql, conn))
    {
        using(OdbcDataReader dr = comm.ExecuteReader())
        {
            while (dr.Read())
            {
                //codes here...
            }
        }
        dr.Close();
    }
    conn.Close();
}

这会更合适吗?

是的,你可以只使用using - 它会为你调用Dispose

您也可以省略Close,因为Dispose会为您调用。

using (OdbcConnection conn = new OdbcConnection())
{
    conn.Open();
    using(OdbcCommand comm = new OdbcCommand(sql, conn))        
    using(OdbcDataReader dr = comm.ExecuteReader())
    {
        while (dr.Read())
        {
            //codes here...
        }
    }            
}

第二个示例是合适的(除了在调用Closedr不在范围内 - Dispose也经常为这些类型的事情调用Close)作为

using(IDisposable foo = ...)
{
    //Do stuff using foo
}

相当于

IDisposable foo = ...;
try
{
    //Do stuff using foo
}
finally
{
    foo.Dispose();
}

最新更新