在 C# 中销毁结构对象?

Destroying a struct object in C#?(在 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# 中销毁结构对象?

基础教程推荐