gpt4 book ai didi

.net - 当对象超出 .Net 的范围时可以运行代码吗?

转载 作者:行者123 更新时间:2023-12-04 16:37:32 25 4
gpt4 key购买 nike

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

最佳答案

using 构造最接近您想要的:

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

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

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

关于.net - 当对象超出 .Net 的范围时可以运行代码吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1423027/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com