2009-09-14 44 views
5

只要變量在.Net語言中丟失範圍,是否有任何方法可以「自動」運行終結/析構函數代碼?在我看來,由於垃圾收集器在不確定的時間運行,析構函數代碼不會在變量失去作用域時立即運行。我意識到我可以從IDisposable繼承,並在我的對象上顯式調用Dispose,但我希望可能會有更多的解決方案,類似於non.Net C++處理對象銷燬的方式。當.NET中的對象超出範圍時,可以運行代碼嗎?

期望的行爲(C#):

public class A { 
    ~A { [some code I would like to run] } 
} 

public void SomeFreeFunction() { 
    SomeFreeSubFunction(); 
    // At this point, I would like my destructor code to have already run. 
} 

public void SomeFreeSubFunction() { 
    A myA = new A(); 
} 

不太理想的:

public class A : IDisposable { 
    [ destructor code, Dispose method, etc. etc.] 
} 

public void SomeFreeFunction() { 
    SomeFreeSubFunction(); 
} 

public void SomeFreeSubFunction() { 
    A myA = new A(); 
    try { 
     ... 
    } 
    finally { 
     myA.Dispose(); 
    } 
} 

回答

9

你想要什麼,以構建最接近即使發生異常,也會自動調用。但是你的班級必須實施IDisposable。

但這並不意味着該對象從內存中刪除。你無法控制。

+0

(+1)很好地注意「using」是使用Dispose方法的簡寫,特別是不用於使用析構函數並從內存中刪除對象。 – 2009-09-14 19:36:06

4

與實施IDisposable接口的對象的使用關鍵字做到了這一點。

例如:

using(FileStream stream = new FileStream("string", FileMode.Open)) 
{ 
    // Some code 
} 

這是由編譯器替換成:

using (MyClass o = new MyClass()) 
{ 
... 
} 

Dispose()方法是:

FileStream stream = new FileStream("string", FileMode.Open); 
try 
{ 
    // Some code 
} 
finally 
{ 
    stream.Dispose(); 
} 
3

不幸的是,沒有。

你最好的選擇是實施IDisposableIDisposable pattern

+0

參見http://www.bluebytesoftware.com/blog/PermaLink.aspx?guid=88e62cdf-5919-4ac7-bc33-20c06ae539ae – TrueWill 2009-09-15 02:16:49

相關問題