当对象超出 .Net 范围时可以运行代码吗?
在 .Net 语言中,一旦变量失去作用域,是否有任何方法可以“自动”运行终结/析构函数代码?在我看来,由于垃圾收集器在不确定的时间运行,因此一旦变量失去作用域,析构函数代码就不会运行。我意识到我可以继承 IDisposable 并在我的对象上显式调用 Dispose,但我希望可能有一个更不干涉的解决方案,类似于非 .Net C++ 处理对象销毁的方式。
期望的行为 (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();
}
}
Is there any way to "automatically" run finalization / destructor code as soon as a variable loses scope in a .Net language? It appears to me that since the garbage collector runs at an indeterminate time, the destructor code is not run as soon as the variable loses scope. I realize I could inherit from IDisposable and explicitly call Dispose on my object, but I was hoping that there might be a more hands-off solution, similar to the way non-.Net C++ handles object destruction.
Desired behavior (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();
}
Less desirable:
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();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
using 构造最接近您想要的:
即使发生异常,也会自动调用 Dispose() 。但你的类必须实现 IDisposable。
但这并不意味着该对象已从内存中删除。你对此无法控制。
The using construct comes closest to what you want:
Dispose() is called automatically, even if an exception occurred. But your class has to implement IDisposable.
But that doesn't mean the object is removed from memory. You have no control over that.
带有实现 IDisposable 的对象的 using 关键字就是这样做的。
例如:
编译器将其替换为:
The using keyword with an object implementing IDisposable does just that.
For instance:
This is replaced by the compiler to:
不幸的是,没有。
最好的选择是使用 IDisposable 实现="http://www.codeproject.com/KB/cs/idisposable.aspx" rel="nofollow noreferrer">IDisposable 模式。
Unfortunately, no.
Your best option is to implement IDisposable with the IDisposable pattern.