C#.net中的using语法

C#.net中的using语法,using (SqlCommand cmd = new SqlCommand(SQLString, connection))
2008-11-3 10:17
提问者: haruno2005 | 浏览次数:1793次
public static int ExecuteSql(string SQLString)
        {
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                using (SqlCommand cmd = new SqlCommand(SQLString, connection))
                {
                    try
                    {
                        connection.Open();
                        int rows = cmd.ExecuteNonQuery();
                        return rows;
                    }
                    catch (System.Data.SqlClient.SqlException e)
                    {
                        connection.Close();
                        throw e;
                    }
                    finally
                    {
                        cmd.Dispose();
                        connection.Close();
                    }
                }
            }
        }

其中using (SqlCommand cmd = new SqlCommand(SQLString, connection))这句为什么要这样写呢?直接写SqlCommand cmd = new SqlCommand(SQLString, connection不就可以了吗?
为什么还要用using()包围呀,这样写有什么好处吗?
最好能引用微软官方解释。
满意回答 
1. 如果你需要使用一个对象,这个对象需要占用很多紧缺的资源,使用完成后需要马上释放掉的话,建议使用using语句
2. 这样写是为了避免资源释放不及时导致的冲突或性能问题
3. 这样写的话处是减少因为争抢资源发生冲突或性能问题的概率
4. 以下为微软官方关于using语句的解释

提供能确保正确使用 IDisposable 对象的方便语法。

语法
  复制代码 
        using (Font font1 = new Font("Arial", 10.0f)) {
.. byte charset = font1.GdiCharSet;
}
 

备注
File 和 Font 是访问非托管资源(本例中为文件句柄和设备上下文)的托管类型的示例。有许多其他类别的非托管资源和封装这些资源的类库类型。所有这些类型都必须实现 IDisposable 接口。

按照规则,当使用 IDisposable 对象时,应在 using 语句中声明和实例化此对象。using 语句按照正确的方式调用对象上的 Dispose 方法,并(在您按照前面所示方式使用它时)会导致在调用 Dispose 时对象自身处于范围之外。在 using 块中,对象是只读的并且无法进行修改或重新分配。

using 语句确保调用 Dispose,即使在调用对象上的方法时发生异常也是如此。通过将对象放入 try 块中,并在调用 finally 块中的 Dispose,可以获得相同的结果;实际上,这就是编译器转换 using 语句的方式。前面的代码示例在编译时将扩展到以下代码(请注意,使用额外的大括号为对象创建有限范围):

{

  复制代码 
  Font font1 = new Font("Arial", 10.0f);
  try
  {
    byte charset = font1.GdiCharSet;
  }
  finally
  {
    if (font1 != null)
      ((IDisposable)font1).Dispose();
  }
}
 

可以将多个对象与 using 语句一起使用,但必须在 using 语句中声明这些对象,如以下示例所示:

  复制代码 
        using (Font font3 = new Font("Arial", 10.0f), 
           font4 = new Font("Arial", 10.0f))
{
    // Use font3 and font4.
}
 

可以实例化资源对象,然后将变量传递给 using 语句,但这不是最佳做法。在这种情况下,该对象将在控制权离开 using 块之后保持在范围内,即使它可能将不再具有对其非托管资源的访问权也是如此。换句话说,再也不能完全初始化该对象。如果试图在 using 块外部使用该对象,则可能导致引发异常。由于这个原因,通常最好是在 using 语句中实例化该对象并将其范围限制在 using 块中。

  复制代码 
Font font2 = new Font("Arial", 10.0f);
using (font2) // not recommended
{
    // use font2
}
// font2 is still in scope
// but the method call throws an exception
float f = font2.GetHeight();
 
C#中可使用using关键字自动清除对象资源。 

# MyObject.cs 

using System; 



namespace MyProjects 

{ 

public class MyObject : IDisposable 

{ 

public MyObject() 

{ 

} 



public void Dispose ( ) 

{ 

// Dispose 

Console.WriteLine ( "Disposed" ) ; 

// ... 

} 

} 

} 



# Class1.cs 

using System; 



namespace MyProjects 

{ 

public class Class1 

{ 

public Class1() 

{ 

} 



public static void Main ( string[] args ) 

{ 

using ( MyObject myObject = new MyObject ( ) ) 

{ 

Console.WriteLine ( "quit" ) ; 

} 

} 

} 

} 



使用using会自动调用MyObject的Dispose方法. 

如果MyObject未实现IDispose接口,则编译时会出错:无法将类型“MyProjects. MyObject”隐式转换为“System.IDisposable” 

这种写法可替代 

try 

{ //... } 

catch 

{ } 

finnaly 

{ MyObject.Dispose ( ) ; } 
 
 
using 语句封装了IDisposable 接口 。

而IDisposable 接口 定义一种释放分配的资源的方法。

通常我们会这样写:
SqlConnection connection = new SqlConnection(connectionString)
connection.Open();
然后connection.Close();
如果用using()语句,即在最后调用Dispose方法释放资源。 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值