Destroying a struct object in C#?

前端 未结 8 1633
长情又很酷
长情又很酷 2020-12-17 09:49

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

8条回答
  •  难免孤独
    2020-12-17 10:13

    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.)

提交回复
热议问题