Good implementation of weak dictionary in .Net

前端 未结 7 1876
Happy的楠姐
Happy的楠姐 2020-12-14 16:12

Where can I find good implementation of IDictionary which uses weak references inside?

Dictionary should be holding only weak references to values and e

7条回答
  •  清歌不尽
    2020-12-14 17:03

    You'll need to write it yourself. It should be relatively straight forward, implementing the IDictionary interface and then storing the actual values as WeakReferences. You can then check the values on add/select to see if they're still alive.

    Pseudo code - won't really compile:

    public class WeakDictionary  : IDictionary
    {
        private IDictionary _innerDictionary = new Dictionary();
    
    
        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();
            foreach( var pair in _innerDictionary )
            {
                if( ! pair.Value.IsAlive )
                    deadKeys.Add( pair.Key );
            }
    
            foreach( var key in deadKeys )
                _innerDictionary.Remove( key );
        }
    }
    

提交回复
热议问题