/// <summary> /// Get an associate given an indexing object /// </summary> /// <param name='key'> /// The object to find the associate for /// </param> /// <typeparam name='T2'> /// The type of associate to find /// </typeparam> public T2 Get <T2>(object key, Func <object> t2Factory) where T2 : T { //Get the hash code of the indexing object int hash = key.GetHashCode(); List <WeakEntry> entries; //See if we have a reference already if (!references.TryGetValue(hash, out entries)) { //If not the create the reference list references[hash] = entries = new List <WeakEntry>(); } //See if we have an object of the correct type and that the //reference is still alive WeakEntry item = entries.FirstOrDefault(e => e.weakReference.IsAlive && e.weakReference.Target == key && e.associate is T2); if (item == null) { //If not create one if (t2Factory != null) { entries.Add(item = new WeakEntry { weakReference = new WeakReference(key), associate = t2Factory() }); } else { return(default(T2)); } } //Return the associate return((T2)item.associate); }
/// <summary> /// Gets an associated object give an index of another object /// </summary> /// <param name='index'> /// The object to use as an index /// </param> public T this[object key] { get { //Get the hash code of the indexed object int hash = key.GetHashCode(); //Try to get a reference to it List <WeakEntry> entries; if (!references.TryGetValue(hash, out entries)) { //If we failed then create a new entry references[hash] = entries = new List <WeakEntry>(); } //Try to get an associated object of the right type for this //indexer/make sure it is still alive WeakEntry item = entries.FirstOrDefault(e => e.weakReference.IsAlive && e.weakReference.Target == key); //Check if we got one if (item == null) { //If we didn't then create a new one if (factory != null) { entries.Add(item = new WeakEntry { weakReference = new WeakReference(key), associate = factory() }); } else { return(null); } } //Return the associated object return((T)item.associate); } }