我在超出范围后遇到析构函数问题(它正在调用但过了一段时间后需要对表单执行操作,例如更改单选按钮),也许我的代码中有错误。看一看:
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()");
}
}
}
最佳答案
是的,因为这不是 C++。不能保证在对象离开其声明范围后立即调用终结器(不是 C++ 中的析构函数),它会在 GC 决定突袭并在您之后进行清理时调用。
请问您为什么一开始就使用终结器?您是否维护对需要尽可能确定地释放的非托管资源的引用(如果是这样,请阅读 IDisposable 接口(interface))? C# 终结器的用例很少而且相差甚远,实现它们并不常见。
关于C# 析构函数在超出范围后不调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10985045/