简体   繁体   English

在C#中是否有Java WeakHashMap类的等价物?

[英]Is there an equivalent for Java WeakHashMap class in C#?

Is there a C# class that provides map with weak keys or/and weak values? 是否有一个C#类提供弱键或/和弱值的映射? Or at least WeakHashMap like functionality. 或至少WeakHashMap之类的功能。

In .Net 3.5 and below, there is no such structure available. 在.Net 3.5及更低版本中,没有这样的结构可用。 However I wrote up one for a side project and posted the code at the following location . 但是我为一个辅助项目编写了一个,并将代码发布在以下位置

Starting .NET 4.0, there is a structure available called ConditionalWeakTable in the Runtime.CompilerServices namespace that also does the trick. 从.NET 4.0开始,Runtime.CompilerServices命名空间中有一个名为ConditionalWeakTable的结构也可以实现。

Prior to .NET 4, the CLR did not provide the functionality necessary to implement a map of this form. 在.NET 4之前,CLR没有提供实现此表单映射所需的功能。 In particular, Java provides the ReferenceQueue<T> class, which WeakHashMap uses to manage the weak keys in the map. 特别是,Java提供了ReferenceQueue<T>类, WeakHashMap使用它来管理映射中的弱键。 Since there is no equivalent to this class in .NET, there is no clean way to build an equivalent Dictionary . 由于.NET中没有与此类相同的内容,因此没有简洁的方法来构建等效的Dictionary

In .NET 4, a new class ConditionalWeakTable<TKey, TValue> was added as part of an effort to improve the ability of the CLR to support dynamic languages. 在.NET 4中,添加了一个新类ConditionalWeakTable<TKey, TValue> ,作为提高CLR支持动态语言的能力的一部分。 This class uses a new type of garbage collection handle, which is implemented within the CLR itself and exposed in mscorlib.dll through the internal DependentHandle structure. 此类使用新类型的垃圾收集句柄,该句柄在CLR本身内实现,并通过内部DependentHandle结构在mscorlib.dll中公开。

This means the following for you: 这意味着以下内容:

  1. There is no equivalent to WeakHashMap prior to .NET 4. 在.NET 4之前没有与WeakHashMap等效的东西。
  2. Starting with .NET 4, and continuing at least through .NET 4.5.1, the only way to support the functionality of WeakHashMap is to use the ConditionalWeakTable class (which is sealed). 从.NET 4开始,至少继续通过.NET 4.5.1,支持WeakHashMap功能的唯一方法是使用ConditionalWeakTable类(它是密封的)。

Additional information is found in the following post: 其他信息可在以下帖子中找到:
Is it possible to create a truely weak-keyed dictionary in C#? 是否有可能在C#中创建一个真正弱键的字典?

The closest platform equivalent is probably a Dictionary<K, WeakReference<V>> . 最接近的平台等价物可能是Dictionary<K, WeakReference<V>> That is, it's just a regular dictionary, but with the values being weak references. 也就是说,它只是一个普通的字典,但值是弱引用。

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

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