2016-09-23 59 views
2

我正在評論一些C#代碼,並且因爲我已經與C#合作過了一段時間,所以我想確保我的直覺是正確的。在這段代碼中我看到了使用塊內的一些地方,像下面這樣做:C#使用清除處理

using(StreamWriter thing = new StreamWriter()) { 

    DataSet DS = SQLQueryMethod(); 
    do stuff to DS and log that stuff to the a log file using thingy... 

    DS.clear(); 
    DS.Dispose(); 
} 

現在,我已經做的一點點研究對這個問題,以及通過我的失敗回頭幾年記憶和我認爲有很多方法可以做到這一點會更好。我想知道哪個更「標準」/「最好的方法」。我在想下面的數字1是做這件事的最好方法。

在此先感謝。

  1. 添加數據集的using語句,這樣它獲取與using語句的範圍結束時自動處置,避免了兩者的清晰和處置的需要。我這樣做:

    using(StreamWriter thing = new StreamWriter(), DataSet DS = new DataSet()) { 
    
        DS = SQLQueryMethod() 
        do stuff to DS{...} 
    
    } 
    
  2. 只需調用數據集DS的處置,因爲我覺得在清除一個dispose只是之前是沒有用的。

  3. 實際上有必要以原來的方式來做。

+0

這個問題可能屬於http://codereview.stackexchange.com但回答你的問題是,是,是的,但我還是認爲你需要2個單獨使用 –

+0

只要我在一個實例化同一個對象的方法中看到'.Dispose()',我總是會畏縮,並且看到如何將它重寫成'using'模式,這在幾乎所有的時候都是非常容易的。 –

+0

我看到多個使用語句的幾個答案,而不是將多個項目添加到單個使用語句,他們之間有區別嗎? 示例:使用(意達,itemB) { } VS 使用(意達) 使用(itemB) { } –

回答

6

多個「使用說明」可用於如下:

using (StreamWriter thing = new StreamWriter()) 
using (DataSet DS = new DataSet()) 
{ 
    DS = SQLQueryMethod(); 
    //do stuff .... 
} 

由於StreamWriter的程序和數據集實現了所需的Dispose()方法中IDisposable接口,無需顯式調用它之後

+4

如果你想保存一行,你甚至可以使用'(DataSet DS = SQLQueryMethod())' –

+2

爲什麼每個人都在答案中聲明'new DataSet()'? 'using'語句不保留原始參考? – flakes

+2

@ flkes - 我不明白 - 這不會編譯:) –

0

正確的方法是處理所有實現IDisposable的東西 - 如

using (var thing = new StreamWriter()) 
using (var ds = SQLQueryMethod()) 
{ 
    do stuff to DS {} 
} 

建議的其他答案是錯的

using(StreamWriter thing = new StreamWriter()) 
using(DataSet DS = new DataSet()) 
{ 
    // this won't compile - DS is in using so it is a read-only variable 
    DS = SQLQueryMethod() 
    do stuff to DS{...} 
} 

參考:Why is a variable declared in a using statement treated as readonly?

+0

問題是關於使用usings和IDisposable。 – alexqc