我超出範圍之後析構函數有問題(它正在調用,但過了一段時間,需要在窗體上進行操作,例如更改單選按鈕),也許我的錯誤碼。看看:C#析構函數超出範圍後不會調用
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
EventLogger.Print += delegate(string output)
{ if (!textBox1.IsDisposed) this.Invoke(new MethodInvoker(() => textBox1.AppendText(output + Environment.NewLine)), null); };
}
private void button1_Click(object sender, EventArgs e)
{
TestClass test = new TestClass();
}
}
public static class EventLogger
{
public delegate void EventHandler(string output);
public static event EventHandler Print;
public static void AddLog(String TextEvent)
{
Print(TextEvent);
}
}
public class TestClass
{
public TestClass()
{
EventLogger.AddLog("TestClass()");
}
~TestClass()
{
EventLogger.AddLog("~TestClass()");
}
}
}
我建議你使用IDisposable模式而不是析構函數。特別是如果你沒有OS級別的句柄。你不應該使用析構函數。 – DarthVader
永遠不要依賴析構函數。 –
另一個說明。你甚至有問題嗎?析構函數在GC時間被調用,並且無法控制。你不能迫使GC進行清理。無論如何,你甚至不需要代碼中的任何desctructor。 – DarthVader