使用封装资源的对象

使用封装资源的对象

MSDN

如果您要编写代码,而该代码使用一个封装资源的对象,您应该确保在使用完该对象时调用该对象的 Dispose 方法。要做到这一点,可以使用 C# 的 using 语句,或使用其他面向公共语言运行库的语言来实现 try/finally 块。

C# 的 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();
      }
   }
}

 

使用 C# 的 using 语句,可以在单个语句(该语句在内部同嵌套的 using 语句是等效的)中获取多个资源。有关更多信息及代码示例,请参见 using 语句(C# 参考)

Try/Finally 块

当您用 C# 以外的语言编写托管代码时,如果该代码使用一个封装资源的对象,请使用 try/finally 块来确保调用该对象的 Dispose 方法。下面的代码示例将创建并清理 Resource 类的实例,如 Visual Basic 示例实现 Dispose 方法中所示。

 
class myApp
   Public Shared Sub Main()
      Resource r1 = new Resource()
      Try
         ' Do something with the object.
         r1.DoSomething()
      Finally
         ' Check for a null resource.
         If Not (r1 is Nothing) Then
            ' Call the object's Dispose method.
            r1.Dispose()
         End If
      End Try
   End Sub
End Class

 

posted @ 2014-11-25 11:00  Old  阅读(172)  评论(0编辑  收藏  举报