WeakSet<T> 和 Set<Weakref<T>> 的区别

Difference between WeakSet<T> and Set<Weakref<T>>

我最近想知道 Set<Weakref<T>> 相对于 WeakSet<T> 是否有任何缺点。

优点:

缺点:

我是不是漏掉了什么,或者这几乎是一个双赢的局面? Set<Weakref<T>> 版本会阻止垃圾收集器收集吗?

你错过了什么:

WeakSets are collections of objects only. They cannot contain arbitrary values of any type, as Sets can.

The number of objects or their traversal order is immaterial, so a WeakSet is more suitable (and performant) than a Set for tracking object references, especially if a very large number of objects is involved.

MDN source

Set<Weakref<T>> 不会阻止 GC。另请注意,Opera 不支持 WeakRef,但支持 WeakSet