枚举变量可以被垃圾回收吗?
通常,所有引用类型在没有引用时都会被垃圾收集。那么枚举变量呢?即使它超出范围(意味着它没有被更多引用),它也会被垃圾收集吗?
Normally all reference types are garbage collected when it is having no reference. What about a enum variable? will it be garbage collected even if it is out of scope(means it is not referenced more)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
你的问题写得非常混乱。
不收集参考类型。收集引用类型的实例。当实例没有引用时,不会收集它们。当垃圾收集器运行并确定无法从已知的活动根访问引用的对象时,它们就会被收集。。
变量的范围是程序文本的区域,在该区域中可以通过变量的名称来访问该变量。变量的范围仅与其生命周期松散地连接,这就是您所询问的。变量的生命周期可能比程序控制在其范围内的时间段长或短!
另外,完全不清楚“枚举变量会被垃圾收集吗?”是什么意思?变量是存储位置,因此变量必须位于某处。 变量在哪里?它是一个类的一个字段吗?它是局部变量吗?它是 lambda 的封闭外部变量吗?它是枚举类型数组的元素吗?所有这些都会影响与变量关联的存储是否被收集,如果是,则何时收集。
你的问题实际上没有任何意义。你能澄清一下这个问题吗?
您可能还想阅读我对此相关问题的回答:
值类型会收集垃圾吗?
Your question is very confusingly written.
Reference types are not collected. Instances of reference types are collected. And they are not collected when the instance has no references. They are collected when the garbage collector runs and determines that the referenced object cannot be reached from a known-to-be-alive root.
The scope of a variable is the region of program text in which the variable may be accessed by its name. The scope of a variable is only loosely connected to its lifetime, which is what you are asking about. The lifetime of a variable may be longer or shorter than the period of time that program control is in its scope!
Also, it is completely unclear what you mean by "will an enum variable be garbage collected?" Variables are storage locations, so the variable has to be somewhere. Where is the variable? Is it a field of a class? is it a local variable? Is it a closed-over outer variable of a lambda? Is it an element of an array of enumerated type? All of these affect whether the storage associated with the variable is collected, and if it is, when it is collected.
Your question doesn't really make any sense the way you've asked it. Can you clarify the question?
You might also want to read my answer to this related question:
Do value types get Garbage collected?
枚举是一个值类型变量,因此当它超出范围时,它会自动
释放被遗忘。An enum is a value type variable so it is automatically
releasedforgotten when it falls out of scope.C# 中的枚举是一种值类型,因此将遵循值类型的垃圾收集规则,该规则根据该类型的声明范围而延迟。你可以在互联网上找到很多信息。下面是一个从 GC 角度比较引用类型和值类型的示例链接。
http://www.albahari.com/valuevsreftypes.aspx
Enumeration in C# is a value type so will follow the rules of garbage collection for value types, which defers based on declaration scope of that type. You can find a lot information on internet. Here is an example link of reference and value types comparison also from GC perspective.
http://www.albahari.com/valuevsreftypes.aspx