强大的using语句

来源:互联网 发布:c 多线程编程面试题 编辑:程序博客网 时间:2024/05/21 01:47

using web;

using ……;

using……;

相信大家看到using最多的地方应该是类似上面语句,换句话说,引用命名空间

然而,using最强大的功能并不在这里,看看以下的demo

// 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

   }

}

<来自msdn>

关键的解释是这样的:

using 语句中创建一个实例,确保退出 using 语句时在对象上调用 Dispose。当到达 using 语句的末尾,或者如果在语句结束之前引发异常并且控制离开语句块,都可以退出 using 语句。

实例化的对象必须实现 System.IDisposable 接口。

更通俗的理解是在using关键字后面的括号创建的非托管对像(必须实现IDisposable)在using大括号里面使用

之后会自动清理资源,在本地的msdn上面可以看到using 语句生成的il代码里面,实际是建构一个try..catch..

块,并在块里面调用Dispose,这样,我们以后可以常常在项目中为非托管资源加个外壳

using (init obj)

{

    using obj

}