using(){}的使用
来源:互联网 发布:药流对身体的影响 知乎 编辑:程序博客网 时间:2024/05/22 15:29
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使用在对数据库的操作的时候。
阅读全文
0 0
- using 的使用
- using 命令的使用
- using声明的使用
- using关键字的使用
- using的使用方式
- C# using的使用
- using(){}的使用
- C#中using的使用
- C#中using的使用
- C#中using的使用
- 关于单片机的using使用
- Using使用的一个例程
- C#中using的使用
- C# using语句的使用
- using namespace的使用问题
- C++ 中using 的使用
- using使用
- 解开using指令使用的迷惑
- webots自学笔记(二)节点与机器人建模
- 前端上传组件Plupload使用指南
- 清除微信内置浏览器缓存
- poj 2586 Y2K Accounting Bug【贪心】【刷题计划】
- Android基础之AsyncTask的doInBackground方法参数详解
- using(){}的使用
- 数据挖掘-Apriori算法(1)
- java的数据结构和算法
- 文件的上传与下载代码
- 身份证识别+银行卡识别:开启移动互金新体验
- 蓝桥杯 基础练习 十六进制转十进制
- 将服务器上的Oracle数据库导出到本地Oracle数据库的方法
- HDU-2571 命运 (线性dp)
- ntelliJ IDEA在写文档注释的时候光标不跟随或不能输入汉字的解决方法