使用封裝資源的對象

使用封裝資源的對象

MSDN編程

若是您要編寫代碼,而該代碼使用一個封裝資源的對象,您應該確保在使用完該對象時調用該對象的 Dispose 方法。要作到這一點,能夠使用 C# 的 using 語句,或使用其餘面向公共語言運行庫的語言來實現 try/finally 塊。app

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 語句的代碼與下面的代碼等效。spa

 
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# 參考)code

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
相關文章
相關標籤/搜索