Kon*_*rin 30 .net dictionary weak-references
我在哪里可以找到IDictionary
使用弱引用的良好实现?
字典应该只保留对值的弱引用,并最终清除死引用本身.
或者我应该自己写吗?
mad*_*ang 29
ConditionalWeakTable类使用弱键,并在表外没有其他对键的引用时自动删除键/值条目.
你需要自己写.它应该相对简单,实现IDictionary接口,然后将实际值存储为WeakReferences.然后,您可以检查添加/选择的值,看看它们是否仍然存在.
伪代码 - 不会真正编译:
public class WeakDictionary <TKey,TValue> : IDictionary<TKey,TValue>
{
private IDictionary<TKey,WeakReference> _innerDictionary = new Dictionary<TKey,WeakReference>();
public TValue Index[ TKey key ]
{
get{
var reference = _innerDictionary[ key ];
if( reference.IsAlive )
return (TValue)reference.Target;
throw new InvalidOperation( "Key not found." );
}
}
private void Cull()
{
var deadKeys = new List<TKey>();
foreach( var pair in _innerDictionary )
{
if( ! pair.Value.IsAlive )
deadKeys.Add( pair.Key );
}
foreach( var key in deadKeys )
_innerDictionary.Remove( key );
}
}
Run Code Online (Sandbox Code Playgroud)