简体   繁体   English

字典在GC之后如何找到对象?

[英]how does a Dictionary find an object after a GC?

looking at this post: references updated on GC , it seems that the heap could get compacted on a Garbage collection which means that the references would change. 看这篇文章: GC上更新了引用 ,似乎可以在Garbage集合上压缩堆,这意味着引用将发生变化。

Now if I were to put an object in a Dictionary as a key (assume that the object does not implement GetHashCode/Equals), then the reference would be used to determine it's location within it's internal Hash table. 现在,如果我将一个对象作为键放在Dictionary中(假设该对象未实现GetHashCode / Equals),则该引用将用于确定其在内部Hash表中的位置。 Subsequently on a GC, if the reference changes, and I want to lookup the object how would C# find it? 随后在GC上,如果引用发生更改,并且我想查找对象,C#将如何找到它?

The dictionary doesn't use the object's location in memory to do book-keeping - it uses the hash code. 字典不使用对象在内存中的位置进行簿记-它使用哈希码。 The hash code of an object doesn't change when the object is moved in memory, even if it doesn't override GetHashCode() . 即使对象的哈希码没有覆盖GetHashCode() ,它的哈希码也不会改变。 The details about how that works are very much implementation details, but you can definitely rely on GetHashCode() returning the same value before and after compaction (assuming the method hasn't been overridden in some bizarre and awful way). 有关该工作原理的细节非常多地是实现细节,但是您绝对可以依靠GetHashCode()在压缩前后将其返回相同的值(假设该方法尚未以某种怪异和可怕的方式被覆盖)。

While the implementation details can change over time, this blog post has an interesting (and recent) description. 尽管实现的详细信息可能会随时间而变化,但是此博客文章中有一个有趣的(以及最近的)描述。 I believe that's still valid in .NET Core (as of April 2018) based on chasing code in the .NET Core CLR GitHub repo - this is a reasonable starting point, as far as I can see. 我相信基于.NET Core CLR GitHub存储库中的代码,在.NET Core(截至2018年4月)中仍然有效-据我所知, 是一个合理的起点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM