C#using 用法

代码中有一个using的用法,刚开始查看了一些资料说是强制关闭对象的一个命令。今天又查了一些资料,才明白,原来using指令调用了一个方法——Dispose()方法。而Dispose()方法的作用就是释放所有的使用资源。

例:

复制代码
public void ExecuteCommand( string connString,  string commandString )  
{  
  SqlConnection myConnection = new SqlConnection( connString );  
  SqlCommand mySqlCommand = new SqlCommand( commandString,  
    myConnection );  
 
  myConnection.Open();  
  mySqlCommand.ExecuteNonQuery();  
} 
复制代码

这个例子中的两个可处理对象没有被恰当的释放:SqlConnection和SqlCommand。两个对象同时保存在内存里直到析构函数被调用。

解决这个问题的方法就是在使用完命令和链接后就调用它们的Dispose:

复制代码
public void ExecuteCommand( string connString,  string commandString )  
{  
  SqlConnection myConnection = new SqlConnection( connString );  
  SqlCommand mySqlCommand = new SqlCommand( commandString,  
    myConnection );  
 
  myConnection.Open();  
  mySqlCommand.ExecuteNonQuery();  
 
  mySqlCommand.Dispose( );  
  myConnection.Dispose( );  
} 
复制代码

使用using语句也可以很好的实现此功能,而且代码很清晰:

复制代码
public void ExecuteCommand( string connString,  string commandString )  
{  
  using ( SqlConnection myConnection = new   SqlConnection( connString ))  
  {  
    using ( SqlCommand mySqlCommand = new  SqlCommand( commandString, myConnection ))  
    {  
      myConnection.Open();  
      mySqlCommand.ExecuteNonQuery();  
    }  
  }  
} 
复制代码

当你在一个函数内使用一个可处理对象时,using语句是最简单的方法来保证这个对象被恰当的处理掉。当这些对象被分配时,会被编译器放到一个try/finally块中。

复制代码
SqlConnection myConnection = null;  
 
// Example Using clause:  
using ( myConnection = new SqlConnection( connString ))  
{  
  myConnection.Open();  
}  
 
 
// example Try / Catch block:  
try {  
  myConnection = new SqlConnection( connString );  
  myConnection.Open();  
}  
finally {  
  myConnection.Dispose( );  
} 
复制代码
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值