我需要构造一个可序列化的,可观察的字典。 它必须是可观察的,以便我知道它何时发生变化,并且必须是可序列化的,因为我需要能够通过Visual Studios用户设置保存它。
我在这方面找到了considerable amount的帮助,但我对仿制药的限制有些困难。
目前,字典的关键字类型为<System.Windows.Input.Key>
,值为<System.IO.FileInfo>
。
这就是我到目前为止:同样,我需要帮助解决泛型类型的限制:
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( );
} );
}
}
}
我非常肯定我必须在FileInfo
类上实现序列化,但是现在我只想专注于拥有一个可以采用可以序列化的泛型的字典。我希望能够使用XML,但如果我需要使用二进制文件,我可以忍受...
那么,Constraints
Generics
和TKey
需要TValue
这样我可以安全地序列化字典吗?