Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Data/3.2/ItemDictionary_T.cs @ 2806

Last change on this file since 2806 was 2474, checked in by swagner, 15 years ago

Implemented generic EventArgs (#796)

File size: 13.9 KB
Line 
1using System;
2using System.Collections;
3using System.Collections.Generic;
4using System.Text;
5using System.Xml;
6using HeuristicLab.Common;
7using HeuristicLab.Core;
8
9namespace HeuristicLab.Data {
10  /// <summary>
11  /// A dictionary having key-value pairs of the type <see cref="IItem"/>.
12  /// </summary>
13  /// <typeparam name="K">The type of the keys, which must implement the interface <see cref="IItem"/>.</typeparam>
14  /// <typeparam name="V">The type of the values, which must imlement the interface <see cref="IItem"/>.</typeparam>
15  public class ItemDictionary<K,V> : ItemBase, IDictionary<K,V>
16    where K : IItem
17    where V : IItem{
18    private Dictionary<K, V> dict;
19
20    /// <summary>
21    /// Gets the dictionary of key-value pairs.
22    /// </summary>
23    public Dictionary<K, V> Dictionary {
24      get { return dict; }
25    }
26
27    /// <summary>
28    /// Initializes a new instance of <see cref="ItemDictionary&lt;TKey,TValue&gt;"/>.
29    /// </summary>
30    /// <remarks>Creates a new <see cref="Dictionary"/>
31    /// having <see cref="IItem"/> as type of keys and values
32    /// and a new <see cref="IItemKeyComparer&lt;T&gt;"/> as <see cref="IEqualityComparer"/>.</remarks>
33    public ItemDictionary() {
34      dict = new Dictionary<K, V>(new IItemKeyComparer<K>());
35    }
36
37    #region ItemBase Members
38    /// <summary>
39    /// Creates a new instance of <see cref="ItemDictionaryView&lt;K,V&gt;"/>.
40    /// </summary>
41    /// <returns>The created instance as <see cref="ItemDictionaryView&lt;K,V&gt;"/>.</returns>
42    public override IView CreateView() {
43      return new ItemDictionaryView<K,V>(this);
44    }
45
46    /// <summary>
47    /// Clones the current instance and adds it to the dictionary <paramref name="clonedObjects"/>.
48    /// </summary>
49    /// <remarks>Also the keys and values in the dictionary are cloned and saved to the dictionary <paramref name="clonedObjects"/>,
50    /// when they are not already contained (deep copy).</remarks>
51    /// <param name="clonedObjects">A dictionary of all already cloned objects.</param>
52    /// <returns>The cloned instance as <see cref="ItemDictionary&lt;K,V&gt;"/>.</returns>
53    public override object Clone(IDictionary<Guid, object> clonedObjects) {
54      ItemDictionary<K,V> clone = new ItemDictionary<K,V>();
55      clonedObjects.Add(Guid, clone);
56      foreach (KeyValuePair<K, V> item in dict) {
57        clone.dict.Add((K) Auxiliary.Clone(item.Key, clonedObjects), (V) Auxiliary.Clone(item.Value, clonedObjects));
58      }
59      return clone;
60    }
61
62    /// <summary>
63    /// Saves the current instance as <see cref="XmlNode"/> in the specified <paramref name="document"/>.
64    /// </summary>
65    /// <remarks>Every key-value pair is saved as new child node with the tag name "KeyValuePair".<br/>
66    /// In the child node the key is saved as a new child node with the tag name "Key".<br/>
67    /// The value is also saved as new child node with the tag name "Val".
68    /// </remarks>
69    /// <param name="name">The (tag)name of the <see cref="XmlNode"/>.</param>
70    /// <param name="document">The <see cref="XmlDocument"/> where the data is saved.</param>
71    /// <param name="persistedObjects">A dictionary of all already persisted objects. (Needed to avoid cycles.)</param>
72    /// <returns>The saved <see cref="XmlNode"/>.</returns>
73    public override XmlNode GetXmlNode(string name, XmlDocument document, IDictionary<Guid, IStorable> persistedObjects) {
74      XmlNode node = base.GetXmlNode(name, document, persistedObjects);
75      foreach (KeyValuePair<K, V> item in dict) {
76        XmlNode keyNode = PersistenceManager.Persist("Key", item.Key, document, persistedObjects);
77        XmlNode valueNode = PersistenceManager.Persist("Val", item.Value, document, persistedObjects);
78        XmlNode pairNode = document.CreateNode(XmlNodeType.Element, "KeyValuePair", null);
79        pairNode.AppendChild(keyNode);
80        pairNode.AppendChild(valueNode);
81        node.AppendChild(pairNode);
82      }
83      return node;
84    }
85
86    /// <summary>
87    /// Loads the persisted matrix from the specified <paramref name="node"/>.
88    /// </summary>
89    /// <remarks>All key-value pairs must be saved as child nodes of the node. <br/>
90    /// Every child node has to contain two child nodes itself, one for the key, having the tag name "Key",
91    /// and one for the value, having the tag name "Val" (see <see cref="GetXmlNode"/>).</remarks>
92    /// <param name="node">The <see cref="XmlNode"/> where the instance is saved.</param>
93    /// <param name="restoredObjects">The dictionary of all already restored objects. (Needed to avoid cycles.)</param>
94    public override void Populate(XmlNode node, IDictionary<Guid, IStorable> restoredObjects) {
95      base.Populate(node, restoredObjects);
96      for (int i = 0; i < node.ChildNodes.Count; i++) {
97        K key = (K) PersistenceManager.Restore(node.ChildNodes[i].SelectSingleNode("Key"), restoredObjects);
98        V val = (V) PersistenceManager.Restore(node.ChildNodes[i].SelectSingleNode("Val"), restoredObjects);
99        dict[key] = val;
100      }
101    }
102
103    /// <summary>
104    /// The string representation of the dictionary
105    /// </summary>
106    /// <returns>The elements of the dictionary as string, each key-value pair in the format
107    /// <c>Key:Value</c>, separated by a semicolon. <br/>
108    /// If the dictionary contains no entries, "Empty Dictionary" is returned.</returns>
109    public override string ToString() {
110      if (dict.Count > 0) {
111        StringBuilder builder = new StringBuilder();
112        foreach (KeyValuePair<K, V> item in dict) {
113          builder.Append(item.Key.ToString());
114          builder.Append(":");
115          builder.Append(item.Value.ToString());
116          builder.Append("; ");
117        }
118        return builder.ToString();
119      } else {
120        return "Empty Dictionary";
121      }
122    }
123    #endregion
124
125    #region IDictionary<K,V> Members
126
127    ///// <summary>
128    ///// Adds a new key value pair to the dictionary.
129    ///// </summary>
130    /// <inheritdoc cref="System.Collections.Generic.Dictionary&lt;K,V&gt;.Add"/>
131    /// <remarks>Calls <see cref="OnItemAdded"/>.</remarks>
132    ///// <param name="key">The key to add.</param>
133    ///// <param name="value">The value to add.</param>
134    public void Add(K key, V value) {
135      dict.Add(key, value);
136      OnItemAdded(key, value);
137    }
138
139    /// <inheritdoc cref="System.Collections.Generic.Dictionary&lt;TKey,TValue&gt;.ContainsKey"/>
140    public bool ContainsKey(K key) {
141      return dict.ContainsKey(key);
142    }
143
144    /// <inheritdoc cref="System.Collections.Generic.Dictionary&lt;TKey,TValue&gt;.Keys"/>
145    public ICollection<K> Keys {
146      get { return dict.Keys; }
147    }
148
149    /// <summary>
150    /// Removes a key-value pair having the specified <paramref name="key"/>.
151    /// </summary>
152    /// <remarks>Calls <see cref="OnItemRemoved"/>.</remarks>
153    /// <param name="key">The key of the key-value pair, which should be removed.</param>
154    /// <returns><c>true</c> if the key was found and successfully removed,
155    /// <c>false</c> if the key was not found.</returns>
156    public bool Remove(K key) {
157      V value = dict[key];
158      bool removed = dict.Remove(key);
159      OnItemRemoved(key, value);
160      return removed;
161    }
162
163    /// <inheritdoc cref="System.Collections.Generic.Dictionary&lt;K,V&gt;.TryGetValue"/>
164    public bool TryGetValue(K key, out V value) {
165      return dict.TryGetValue(key, out value);
166    }
167
168    /// <inheritdoc cref="System.Collections.Generic.Dictionary&lt;TKey,TValue&gt;.Values"/>
169    public ICollection<V> Values {
170      get { return dict.Values; }
171    }
172
173    /// <summary>
174    /// Gets or sets the value of a specified <paramref name="key"/>.
175    /// </summary>
176    /// <param name="key">The key of the value which should be received or changed.</param>
177    /// <returns>The value of the <paramref name="key"/>.</returns>
178    public V this[K key] {
179      get { return dict[key]; }
180      set { dict[key] = value; }
181    }
182
183    #endregion
184
185    #region ICollection<KeyValuePair<K,V>> Members
186
187    /// <summary>
188    /// Adds a key-value pair to the current instance.
189    /// </summary>
190    /// <remarks>Calls <see cref="OnItemAdded"/>.</remarks>
191    /// <param name="item">The key-value pair to add.</param>
192    public void Add(KeyValuePair<K, V> item) {
193      dict.Add(item.Key, item.Value);
194      OnItemAdded(item.Key, item.Value);
195    }
196
197    ///// <summary>
198    ///// Empties the dictionary.
199    ///// </summary>
200    /// <inheritdoc cref="System.Collections.Generic.Dictionary&lt;K,V&gt;.Clear"/>
201    /// <remarks>Calls <see cref="OnCleared"/>.</remarks>
202    public void Clear() {
203      dict.Clear();
204      OnCleared();
205    }
206
207    /// <summary>
208    /// Checks whether the specified key-value pair exists in the current instance of the dictionary.
209    /// </summary>
210    /// <param name="item">The key-value pair to check.</param>
211    /// <returns><c>true</c> if both, the key and the value exist in the dictionary,
212    /// <c>false</c> otherwise.</returns>
213    public bool Contains(KeyValuePair<K, V> item) {
214      return (dict.ContainsKey(item.Key) && dict[item.Key].Equals(item.Value));
215    }
216
217    /// <summary>
218    /// TODO
219    /// </summary>
220    /// <param name="array"></param>
221    /// <param name="arrayIndex"></param>
222    public void CopyTo(KeyValuePair<K, V>[] array, int arrayIndex) {
223      throw new NotImplementedException();
224    }
225
226    /// <inheritdoc cref="System.Collections.Generic.Dictionary&lt;K,V&gt;.Count"/>
227    public int Count {
228      get { return dict.Count; }
229    }
230
231    /// <summary>
232    /// Checks whether the dictionary is read-only.
233    /// </summary>
234    /// <remarks>Always returns <c>false</c>.</remarks>
235    public bool IsReadOnly {
236      get { return false; }
237    }
238
239    /// <summary>
240    /// Removes the specified key-value pair.
241    /// </summary>
242    /// <remarks>Calls <see cref="OnItemRemoved"/> when the removal was successful.</remarks>
243    /// <param name="item">The key-value pair to remove.</param>
244    /// <returns><c>true</c> if the removal was successful, <c>false</c> otherwise.</returns>
245    public bool Remove(KeyValuePair<K, V> item) {
246      bool removed = dict.Remove(item.Key);
247      if (removed) {
248        OnItemRemoved(item.Key, item.Value);
249      }
250      return removed;
251    }
252    #endregion
253
254    #region IEnumerable<KeyValuePair<K,V>> Members
255    /// <inheritdoc cref="System.Collections.Generic.Dictionary&lt;K,V&gt;.GetEnumerator"/>
256    public IEnumerator<KeyValuePair<K, V>> GetEnumerator() {
257      return dict.GetEnumerator();
258    }
259    #endregion
260
261    #region IEnumerable Members
262    /// <inheritdoc cref="System.Collections.Generic.Dictionary&lt;K,V&gt;.GetEnumerator"/>
263    IEnumerator IEnumerable.GetEnumerator() {
264      return dict.GetEnumerator();
265    }
266    #endregion
267
268    #region Event Handler
269    /// <summary>
270    /// Occurs when a new item is added to the dictionary.
271    /// </summary>
272    public event EventHandler<EventArgs<IItem, IItem>> ItemAdded;
273    /// <summary>
274    /// Fires a new <c>ItemAdded</c> event.
275    /// </summary>
276    /// <remarks>Calls <see cref="HeuristicLab.Core.ItemBase.OnChanged"/>.</remarks>
277    /// <param name="key">The key that was added.</param>
278    /// <param name="value">The value that was added.</param>
279    protected virtual void OnItemAdded(K key, V value) {
280      if (ItemAdded != null)
281        ItemAdded(this, new EventArgs<IItem, IItem>(key, value));
282      OnChanged();
283    }
284
285    /// <summary>
286    /// Occurs when an item is removed from the dictionary.
287    /// </summary>
288    public event EventHandler<EventArgs<IItem, IItem>> ItemRemoved;
289    /// <summary>
290    /// Fires a new <c>ItemRemoved</c> event.
291    /// </summary>
292    /// <remarks>Calls <see cref="HeuristicLab.Core.ItemBase.OnChanged"/>.</remarks>
293    /// <param name="key">The key that was removed.</param>
294    /// <param name="value">The value that was removed</param>
295    protected virtual void OnItemRemoved(K key, V value) {
296      if (ItemRemoved != null)
297        ItemRemoved(this, new EventArgs<IItem, IItem>(key, value));
298      OnChanged();
299    }
300
301    /// <summary>
302    /// Occurs when the dictionary is emptied.
303    /// </summary>
304    public event EventHandler Cleared;
305    /// <summary>
306    /// Fires a new <c>Cleared</c> event.
307    /// </summary>
308    /// <remarks>Calls <see cref="HeuristicLab.Core.ItemBase.OnChanged"/>.</remarks>
309    protected virtual void OnCleared() {
310      if (Cleared != null)
311        Cleared(this, new EventArgs());
312      OnChanged();
313    }
314    #endregion
315
316    #region IEqualityComparer
317    /// <summary>
318    /// Compares two keys with each other.
319    /// </summary>
320    /// <typeparam name="T">The type of the keys.</typeparam>
321    internal sealed class IItemKeyComparer<T> : IEqualityComparer<T>
322        where T : IItem {
323      /// <summary>
324      /// Checks whether two keys are equal to each other.
325      /// </summary>
326      /// <param name="x">Key number one.</param>
327      /// <param name="y">Key number two.</param>
328      /// <returns><c>true</c> if the two keys are the same, <c>false</c> otherwise.</returns>
329      public bool Equals(T x, T y) {
330        if (x is IComparable) {
331          return (((IComparable) x).CompareTo(y) == 0);
332        }
333        if (y is IComparable) {
334          return (((IComparable) y).CompareTo(x) == 0);
335        }
336        return x.Equals(y);
337      }
338
339      /// <summary>
340      /// Serves as a hash function for a particular type.
341      /// </summary>
342      /// <param name="obj">The object where the hash code is searched for.</param>
343      /// <returns>A hash code for the given <paramref name="obj"/>.</returns>
344      public int GetHashCode(T obj) {
345        if (obj is IObjectData) {
346          return ((IObjectData) obj).Data.GetHashCode();
347        }
348        return obj.Guid.GetHashCode();
349      }
350    }
351    #endregion
352  }
353}
Note: See TracBrowser for help on using the repository browser.