一旦变量失去.Net语言的范围,有没有办法“自动”运行终结/析构函数代码?在我看来,由于垃圾收集器在不确定的时间运行,因此一旦变量失去范围,析构函数代码就不会运行。我意识到我可以从IDisposable继承并在我的对象上显式调用Dispose,但是我希望可能有更多不干涉的解决方案,类似于non.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();
}
}
答案 0 :(得分:9)
using构造最接近你想要的:
using (MyClass o = new MyClass())
{
...
}
即使发生异常,也会自动调用Dispose()。但是你的班级必须实现IDisposable。
但这并不意味着该对象已从内存中删除。你无法控制它。
答案 1 :(得分:4)
带有实现IDisposable的对象的using关键字就是这样做的。
例如:
using(FileStream stream = new FileStream("string", FileMode.Open))
{
// Some code
}
编译器将其替换为:
FileStream stream = new FileStream("string", FileMode.Open);
try
{
// Some code
}
finally
{
stream.Dispose();
}
答案 2 :(得分:3)
不幸的是,没有。
您最好的选择是使用IDisposable实施IDisposable pattern。