Destroying a struct object in C#?(在 C# 中销毁结构对象?)
问题描述
我有点困惑,在 C# 中只有引用类型会被垃圾收集.这意味着 GC 只选择引用类型进行内存释放.那么值类型也会占用堆栈内存呢?
I am a bit confused about the fact that in C# only the reference types get garbage collected. That means GC picks only the reference types for memory de-allocation. So what happens with the value types as they also occupy memory on stack ?
推荐答案
首先,它们是在堆栈上还是堆的一部分取决于它们所属的上下文 - 如果它们在引用中类型,无论如何它们都会在堆上.(无论如何,您应该考虑您真正关心堆栈/堆划分的程度 - 正如 Eric Lippert 所写,它是 主要是实现细节.)
For a start, whether they're on the stack or part of the heap depends on what context they're part of - if they're within a reference type, they'll be on the heap anyway. (You should consider how much you really care about the stack/heap divide anyway - as Eric Lippert has written, it's largely an implementation detail.)
然而,基本上值类型的内存在上下文被回收时被回收 - 所以当你从一个方法返回时弹出堆栈时,它会回收"整个堆栈帧.同样,如果值类型值实际上是对象的一部分,那么当该对象被垃圾回收时,内存就会被回收.
However, basically value type memory is reclaimed when the context is reclaimed - so when the stack is popped by you returning from a method, that "reclaims" the whole stack frame. Likewise if the value type value is actually part of an object, then the memory is reclaimed when that object is garbage collected.
简短的回答是您不必担心 :) (当然,这假设您除了内存之外没有任何其他需要担心 - 如果您已经获得了对需要释放的本机句柄的引用的结构,这是一个有点不同的场景.)
The short answer is that you don't have to worry about it :) (This assumes you don't have anything other than the memory to worry about, of course - if you've got structs with references to native handles that need releasing, that's a somewhat different scenario.)
这篇关于在 C# 中销毁结构对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 C# 中销毁结构对象?
基础教程推荐
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- c# Math.Sqrt 实现 2022-01-01
- rabbitmq 的 REST API 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01