2012-08-06 75 views
3

如果我有一個使用塊,我創建一個對象(例如FileStream對象),並且該對象無法創建(返回null,拋出異常等),塊中的代碼是否仍然執行?當c#.net using block失敗時會發生什麼?

using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) { 
    // do stuff with fs here 
} 
// do more stuff after 

如果FileStream構造函數是返回空值(如果FileStream構造函數總是返回一個有效的對象,讓我們只說爲便於討論,有可能返回NULL),將裏面的代碼執行?或者它會跳過「用fs做這些東西」的代碼嗎?

+0

是什麼讓你覺得它仍然會執行而不是崩潰? – perilbrain 2012-08-06 16:30:26

+0

返回null的構造函數? – ken2k 2012-08-06 16:30:31

+0

@ ken2k:正如我所看到的,這僅僅是一個例子。說,而不是一個構造函數,它要求對象服務定位器,工廠或任何東西。實際上,編寫'using(null){}'[編譯並運行良好](http://blogs.msdn.com/b/ericlippert/archive/2011/03/03/danger-will-robinson.aspx)。 .. – Andre 2012-08-06 16:47:05

回答

13
using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) 
{ 
    // do stuff with fs here 
} 
// do more stuff after 

等同於:

FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite) 
try 
{ 
    // do stuff with fs here 
} 
finally 
{ 
    if (fs != null) 
    { 
     ((IDisposable)fs).Dispose(); 
    } 
} 
// do more stuff after 

因此,要回答你的問題:

如果FileStream構造函數是返回空值(如果FileStream 構造函數總是返回一個有效的對象,讓我們只是說爲了 的說法,有可能返回null), 裏面的代碼會執行嗎?

是的,它會的。

顯然大家熟悉C#規格都知道,一個構造函數(無論哪種類型)可以從未回報null哪一種讓你的問題有點不現實。

0

異常將像平常一樣得到處理,即如果您有一個或系統,則通過封閉try ... catch來處理異常。

0

如果它引發異常,它肯定不會執行。如果沒有拋出異常,它將嘗試執行該塊。雖然如果它返回null,我的猜測是,在從內部拋出一個異常並退出之前,它不會有太大的幫助。

0

無論如何,代碼都會執行,因此您需要保護您的代碼免受它影響。舉例來說,這個控制檯應用程序將執行WriteLine

class Program 
{ 
    static void Main(string[] args) 
    { 
     using (null) 
     { 
      Console.WriteLine("Hello."); 
     } 
    } 
} 
相關問題