c#using(){}的使用

using(){}作为语句,用于定义一个范围,在此范围的末尾将释放对象。

using 语句允许程序员指定使用资源的对象应当何时释放资源。using 语句中使用的对象必须实现 IDisposable 接口。此接口提供了 Dispose 方法,该方法将释放此对象的资源。

例如:

using (SqlCommand cmd = new SqlCommand(SQLString, connection))
{
    try
    {
        cmd.Connection = connection;
        cmd.Transaction = trans;
        int rows = cmd.ExecuteNonQuery();
        return rows;
    }
    catch (System.Data.SqlClient.SqlException e)
    {
        //trans.Rollback();
        throw e;
    }
}
 
SqlCommand这个类使用了using语句,转到SqlCommand的定义:

public sealed class SqlCommand : DbCommand, ICloneable
{
    ...
}
 
SqlCommand 继承了DbCommand,在转到DbCommand的定义:

public abstract class DbCommand : Component, IDbCommand, IDisposable
{
    ...
}
 
发现DbCommand 继承了IDisposable,所以前面SqlCommand 可以使用using语句,继续转到IDisposable的定义:

public interface IDisposable
{
    // 摘要: 
    //     执行与释放或重置非托管资源相关的应用程序定义的任务。
    void Dispose();
}
 
IDisposable接口 定义了一个Dispose()方法,用于释放引用对象的资源。

回到上面using(){}的使用:

using (SqlCommand cmd = new SqlCommand(SQLString, connection))
{
    try
    {
        cmd.Connection = connection;
        cmd.Transaction = trans;
        int rows = cmd.ExecuteNonQuery();
        return rows;
    }
    catch (System.Data.SqlClient.SqlException e)
    {
        //trans.Rollback();
        throw e;
    }
}
 
这样我们对using语句是否了解,上面的代码相当于:

{
    SqlCommand cmd = new SqlCommand(SQLString, connection);
    try
    {
        cmd.Connection = connection;
        cmd.Transaction = trans;
        int rows = cmd.ExecuteNonQuery();
        return rows;
    }
    catch (System.Data.SqlClient.SqlException e)
    {
        //trans.Rollback();
        throw e;
    }
    finally
    {
      if (cmd != null)
        ((IDisposable)cmd ).Dispose();
    }
}
 
总结: 
当我们做一些比较占用资源的操作,而且该类或者它的父类继承了IDisposable接口,这样就可以使用using语句,在此范围的末尾自动将对象释放,常见的using使用在对数据库的操作的时候。
 

猜你喜欢

转载自blog.csdn.net/liu3743120/article/details/85260682