簡體   English   中英

空的“使用中”塊

[英]Empty “using” block

它已經確定這里是一個空的使用塊不是重寫適當的方式Dispose() ,但對於以下情況?

這是空的using塊的合法使用嗎?

try
{
    using (File.OpenRead(sourceFile)) { }
}
catch (FileNotFoundException)
{
    error = "File not found: " + sourceFile;
}
catch (UnauthorizedAccessException)
{
    error = "Not authorized to access file: " + sourceFile;
}
catch (Exception e)
{
    error = "Error while attempting to read file: " + sourceFile + ".\n\n" + e.Message;
}

if (error != null)
    return error;

System.Diagnostics.Process.Start(sourceFile);

不,對於空的using塊,這不是合法用途。

您可以像這樣簡單地編寫try:

try
{
    File.OpenRead(sourceFile).Close();
}

OpenRead()將成功並返回必須關閉(或處置,但我認為.Close()更好地表達您的意圖)的流,否則它將引發異常並且不返回任何內容。

因此,您始終可以只關閉返回值。

(我假設您只是在做其他事情之前檢查了讀訪問權限。但是,請注意,理論上您可能會遇到競爭狀況,因為在進行此檢查與稍后實際打開文件之間,文件的可訪問性可能會發生變化。實際上這不太可能發生,但是您應該意識到這種可能性。)

使用空的using塊沒有太大意義,因為您可以最終在catch鏈的末尾添加並在此處處理Dispose

FileStream fs;
try {

    fs = File.OpenRead(sourceFile); 
}
catch(..) {
}
catch(..) {
}
catch(..) {
}
finally {

  if(fs !=null) {
      fs.Close();
      fs.Dispose();

  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM