using 语句

在 using 语句中创建一个实例,确保退出 using 语句时在对象上调用 Dispose。当到达 using 语句的末尾,或者如果在语句结束之前引发异常并且控制离开语句块,都可以退出 using 语句。
实例化的对象必须实现 System.IDisposable 接口。
示例
// cs_using_statement.cs
// compile with /reference:System.Drawing.dll
using System.Drawing;
class a
{
   public static void Main()
   {
      using (Font MyFont = new Font("Arial", 10.0f), MyFont2 = new Font("Arial", 10.0f))
      {
         // use MyFont and MyFont2
      }   // compiler will call Dispose on MyFont and MyFont2

      Font MyFont3 = new Font("Arial", 10.0f);
      using (MyFont3)
      {
         // use MyFont3
      }   // compiler will call Dispose on MyFont3

   }
}

不实现System.IDisposable接口是不能这样用using的。

本例中的Font类是vs.net自带的一个系统类,已经实现了该接口。
public sealed class Font : MarshalByRefObject, ICloneable,
ISerializable, IDisposable

如果是自己写,一般写法如下:
public class AAA : System.IDisposable
{
public AAA()
{
//
}
public void CC()
{
//
}

public void Dispose()
{
//
}

}



对C#程序员来说,确保经常关闭Connection和DataReader对象的一个简便方法是使用using语句。

Using语句会自动调用留在Using语句范围内的被使用的对象上的Dispose,如下所示:  
//C# 
string connString = "Data Source=localhost;
  Integrated Security=SSPI;Initial Catalog=Northwind;";
using (SqlConnection conn = new SqlConnection(connString)) 
{
  SqlCommand cmd = conn.CreateCommand();
  cmd.CommandText = "SELECT CustomerId, CompanyName FROM Customers";
  
  conn.Open();
  using (SqlDataReader dr = cmd.ExecuteReader()) 
  {
    while (dr.Read())
      Console.WriteLine("{0}/t{1}", dr.GetString(0), dr.GetString(1));
  }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值