using System; using System.Collections; using System.Collections.Generic; using System.Reflection; using Decal.Adapter.Support; namespace Decal.Adapter; public class DisposableObjectDictionary : DisposableByRefObject, IDictionary, ICollection>, IEnumerable>, IEnumerable where T : DisposableByRefObject { private Dictionary items = new Dictionary(); private PropertyInfo keyProperty; public ICollection Keys => items.Keys; public ICollection Values => items.Values; public T this[K key] { get { return items[key]; } set { items[key] = value; } } public int Count => ((ICollection>)items).Count; public bool IsReadOnly => ((ICollection>)items).IsReadOnly; public DisposableObjectDictionary(string keyPropertyName) { keyProperty = typeof(T).GetProperty(keyPropertyName, BindingFlags.Instance | BindingFlags.Public); } protected override void Dispose(bool userCalled) { if (userCalled) { Clear(); } base.Dispose(userCalled); } private void value_Disposing(object sender, EventArgs e) { K key = (K)keyProperty.GetValue(sender, null); ((T)sender).Disposing -= value_Disposing; items.Remove(key); } public void Add(K key, T value) { items.Add(key, value); value.Disposing += value_Disposing; } public bool ContainsKey(K key) { return items.ContainsKey(key); } public bool Remove(K key) { return items.Remove(key); } public bool TryGetValue(K key, out T value) { return items.TryGetValue(key, out value); } public void Add(KeyValuePair item) { items.Add(item.Key, item.Value); } public void Clear() { foreach (T value in items.Values) { try { value.Disposing -= value_Disposing; value.Dispose(); } catch (Exception ex) { Util.WriteLine("GDW_Clear: Exception: {0}", ex.Message); } } items.Clear(); } public bool Contains(KeyValuePair item) { return ((ICollection>)items).Contains(item); } public void CopyTo(KeyValuePair[] array, int arrayIndex) { ((ICollection>)items).CopyTo(array, arrayIndex); } public bool Remove(KeyValuePair item) { return ((ICollection>)items).Remove(item); } public IEnumerator> GetEnumerator() { return ((IEnumerable>)items).GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)items).GetEnumerator(); } }