开发者

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? Or 开发者_Python百科at least WeakHashMap like functionality.


In .Net 3.5 and below, there is no such structure available. 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.


Prior to .NET 4, the CLR did not provide the functionality necessary to implement a map of this form. In particular, Java provides the ReferenceQueue<T> class, which WeakHashMap uses to manage the weak keys in the map. Since there is no equivalent to this class in .NET, there is no clean way to build an equivalent 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. 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.

This means the following for you:

  1. There is no equivalent to WeakHashMap prior to .NET 4.
  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).

Additional information is found in the following post:
Is it possible to create a truely weak-keyed dictionary in C#?


The closest platform equivalent is probably a Dictionary<K, WeakReference<V>>. That is, it's just a regular dictionary, but with the values being weak references.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜