I need to construct a serializable, observable dictionary. It must be observable so that I know when it changes, and it must be serializable because I need to be able to save it via Visual Studios User Settings.
I have found a considerable amount of help in this regard, but I am having some difficulty with the constraints for the generics.
For right now, the dictionary will be of have as its Key Type <System.Windows.Input.Key>
, and as the value <System.IO.FileInfo>
.
This is what I have so far : Again, I need help with the constraints on the generic types :
using System;
using System.Linq;
using System.ComponentModel;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Xml.Serialization;
using System.Xml;
using System.Runtime.Serialization;
namespace System.Collections.ObjectModel {
public class ObservableDictionary<TKey, TValue> :
IDictionary<TKey, TValue>, INotifyCollectionChanged, INotifyPropertyChanged, IXmlSerializable
where TKey : ISerializable
where TValue : class, ISerializable, new() {
private const string CountString = "Count";
private const string IndexerName = "Item[]";
private const string KeysName = "Keys";
private const string ValuesName = "Values";
/*Observable Stuff*/
public Xml.Schema.XmlSchema GetSchema( ) { return null; }
public void ReadXml( Xml.XmlReader reader ) {
while ( reader.Read( ) && !(reader.NodeType == XmlNodeType.EndElement && reader.LocalName == this.GetType().Name ) ) {
TKey Key = reader["Key"] as TKey;
if ( Key == null )
throw new FormatException( );
this[Key] = reader["Value"] as TValue;
}
}
public void WriteXml( Xml.XmlWriter writer ) {
this.Keys.ToList( ).ForEach( K => {
writer.WriteStartElement( "KeyValuePair" );
writer.WriteAttributeString( "Key", K.ToString( ) );
writer.WriteAttributeString( "Value", this[K].ToString( ) );
writer.WriteEndElement( );
} );
}
}
}
I'm pretty certain that I will have to implement serialization on the FileInfo
class, but for now I just want to focus on having a dictionary that can take generics that can be serialized. I was hoping to go with XML but if I need to do it Binary, I can live with that...
So, what Constraints
do I need to put on the Generics
TKey
and TValue
such that I can be safe serializing the dictionary?