我一直在阅读 .NET 中的垃圾收集,希望得到一些澄清。因此,据我所知,如果我声明一个公共(public)共享类变量,GC 将永远不会摆脱它。它是否正确?
另外,私有(private)变量呢?举个例子:
public class myClass
private shared myString As String
public sub ChangeString(newString As String)
myString = newString
end sub
end class
如果没有类的实例,共享变量现在会被 GC 吗?如果我将 ChangeString 更改为共享子会怎样?
最佳答案
So, as I understand it if I declare a public shared class variable, the GC will never get rid of it. Is this correct?
几乎。 GC 不会清理共享变量引用的字符串。
但是,如果您调用
ChangeString
使用新字符串,myString
指向的字符串将不再受此引用的影响,并且可能有资格获得 GC。但是,新字符串(由 newString
引用)现在将成为 myString
的根。变量,防止它被垃圾收集。Would the shared variable now get GCed if there were no instances of the class?
不,共享变量是对象的根,因为它属于类的“类型”,而不是任何实例。
And what if I alter ChangeString to be a shared sub?
这将完全没有效果。
关于.net - 共享变量和垃圾收集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9382658/