using做了什么?

C# 编程语言的 using 语句通过简化必须编写以便创建和清理对象的代码,使得对 Dispose 方法的调用更加自动化。using 语句获得一个或多个资源,执行您指定的语句,然后处置对象。请注意,using 语句只适用于这样的对象:这些对象的生存期不超过在其中构建这些对象的方法。下面的代码示例将创建并清理 ResourceWrapper 类的实例,如 C# 示例实现 Dispose 方法中所示。

 

class myApp
{
   
public static void Main()
   
{
      
using (ResourceWrapper r1 = new ResourceWrapper())
      
{
         
// Do something with the object.
         r1.DoSomething();
      }

   }

}

以上合并了 using 语句的代码与下面的代码等效。

 

 

class myApp
{
   
public static void Main()
   
{
      ResourceWrapper r1 
= new ResourceWrapper();
      
try
      
{
         
// Do something with the object.
         r1.DoSomething();
      }

      
finally
      
{
         
// Check for a null resource.
         if (r1 != null)
         
// Call the object's Dispose method.
         r1.Dispose();
      }

   }

}
posted @ 2008-05-09 10:52  roboth  阅读(368)  评论(3)    收藏  举报