5

一旦变量在.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();
    }
}
4

3 回答 3

9

using 构造最接近您想要的:

using (MyClass o = new MyClass()) 
{
 ...
}

即使发生异常,也会自动调用 Dispose()。但是你的类必须实现 IDisposable。

但这并不意味着该对象已从内存中删除。你无法控制它。

于 2009-09-14T18:04:06.613 回答
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();
}
于 2009-09-14T18:03:57.677 回答
3

很不幸的是,不行。

您最好的选择是使用IDisposable 模式实现IDisposable

于 2009-09-14T18:04:10.530 回答