【发布时间】:2012-06-14 15:35:37
【问题描述】:
超出范围后析构函数出现问题(它正在调用但经过一段时间后需要对表单执行操作,例如更改单选按钮),可能是我的代码有错误。看看:
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 模式而不是析构函数。特别是如果您没有操作系统级别的句柄。你不应该使用析构函数。
-
永远不要依赖析构函数。
-
在另一张纸条上。你有问题吗?析构函数在 GC 时被调用,这是你无法控制的。您也不能强制 GC 进行清理。无论如何,您甚至都不需要代码中的任何析构函数。
标签: c# scope destructor