循环和垃圾收集垃圾

2023-09-02 21:12:35 作者:给我一秒毁坏世界

我工作的一个Web应用程序,我遇到了下面的情况。

 黯淡了作为对象
昏暗我作为整数= 0

尝试

    对于i = 1至5个

        A =新的对象()

        做的东西

        A =没有

    下一个

抓住

最后

   A =没有

结束尝试
 

我是否需要做一个=没有在循环或将垃圾收集清理了?

解决方案

在.NET中,你一般不会需要设置一个变量引用= 没有在C#)。垃圾收集器将清理,最终会。当它超出范围的引用本身将被销毁(无论是在当这个类的对象,最终确定你的方法退出或)。请注意,这并不意味着在对象被破坏,只是引用。对象仍然会被非确定性的收集销毁。

不过,设置你参考= 没有将提供一个提示.NET对象可能是垃圾,并不一定伤害任何东西 - 从$ C一边$ C混乱。如果你要保持它在那里,我建议你从尝试块取出;它已经在最后块,并因此总是被调用。 (除了某些灾难性的例外;!但在这种情况下它不会被调用的尝试块其一)

最后,我不得不承认,我同意格雷格:你的code就没有这种清洁剂。该提示到您的参考大功告成运行是好的,但肯定不是关键。老实说,如果我在code检讨看到这个,我可能有开发商重写它正是如此:

 黯淡了作为对象
昏暗我作为整数= 0

对于i = 1至5个
    A =新的对象()
    做的东西
下一个
 
垃圾分类源自点滴,美好环境始于言行

I am working on a web application and I have run into the following situation.

Dim a as Object
Dim i as Integer = 0

Try

    For i=1 to 5

        a = new Object()

        'Do stuff '

        a = Nothing

    Next

Catch

Finally

   a = Nothing

End Try

Do i need to do the a=Nothing in the loop or will the garbage collector clean a up?

解决方案

In .NET, you generally do not need to set a variable reference = Nothing (null in C#). The garbage collector will clean up, eventually. The reference itself will be destroyed when it goes out of scope (either when your method exits or when the object of this class is finalized.) Note that this doesn't mean the object is destroyed, just the reference to it. The object will still be destroyed non-deterministically by the collector.

However, setting your reference = Nothing will provide a hint to .NET that the object may be garbage, and doesn't necessarily hurt anything -- aside from code clutter. If you were to keep it in there, I'd recommend removing it from Try block; it's already in the Finally block and will therefore always be called. (Aside from certain catastrophic exceptions; but in those cases it wouldn't get called in the Try block either!)

Finally, I have to admit that I agree with Greg: Your code would be cleaner without this. The hint to the runtime that you're done with the reference is nice, but certainly not critical. Honestly, if I saw this in a code review, I'd probably have the developer rewrite it thusly:

Dim a as Object
Dim i as Integer = 0

For i=1 to 5
    a = new Object()
    'Do stuff
Next