2010-05-14 74 views
0

我正在研究XML序列化,並且由於我使用了大量的字典,因此我想將它們序列化。我找到了以下解決方案(我爲此感到非常自豪!:))。控制字典的XML序列<K, T>

[XmlInclude(typeof(Foo))] 
public class XmlDictionary<TKey, TValue> 
{ 
    /// <summary> 
    /// Key/value pair. 
    /// </summary> 
    public struct DictionaryItem 
    { 
     /// <summary> 
     /// Dictionary item key. 
     /// </summary> 
     public TKey Key; 

     /// <summary> 
     /// Dictionary item value. 
     /// </summary> 
     public TValue Value; 
    } 

    /// <summary> 
    /// Dictionary items. 
    /// </summary> 
    public DictionaryItem[] Items 
    { 
     get { 
      List<DictionaryItem> items = new List<DictionaryItem>(ItemsDictionary.Count); 

      foreach (KeyValuePair<TKey, TValue> pair in ItemsDictionary) { 
       DictionaryItem item; 

       item.Key = pair.Key; 
       item.Value = pair.Value; 

       items.Add(item); 
      } 

      return (items.ToArray()); 
     } 
     set { 
      ItemsDictionary = new Dictionary<TKey,TValue>(); 

      foreach (DictionaryItem item in value) 
       ItemsDictionary.Add(item.Key, item.Value); 
     } 
    } 

    /// <summary> 
    /// Indexer base on dictionary key. 
    /// </summary> 
    /// <param name="key"></param> 
    /// <returns></returns> 
    public TValue this[TKey key] 
    { 
     get { 
      return (ItemsDictionary[key]); 
     } 
     set { 
      Debug.Assert(value != null); 
      ItemsDictionary[key] = value; 
     } 
    } 

    /// <summary> 
    /// Delegate for get key from a dictionary value. 
    /// </summary> 
    /// <param name="value"></param> 
    /// <returns></returns> 
    public delegate TKey GetItemKeyDelegate(TValue value); 

    /// <summary> 
    /// Add a range of values automatically determining the associated keys. 
    /// </summary> 
    /// <param name="values"></param> 
    /// <param name="keygen"></param> 
    public void AddRange(IEnumerable<TValue> values, GetItemKeyDelegate keygen) 
    { 
     foreach (TValue v in values) 
      ItemsDictionary.Add(keygen(v), v); 
    } 

    /// <summary> 
    /// Items dictionary. 
    /// </summary> 
    [XmlIgnore] 
    public Dictionary<TKey, TValue> ItemsDictionary = new Dictionary<TKey,TValue>(); 
} 

從此類派生的類以下面的方式進行序列化:

<FooDictionary xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> 
<Items> 
    <DictionaryItemOfInt32Foo> 
    <Key/> 
    <Value/> 
    </DictionaryItemOfInt32XmlProcess> 
<Items> 

這給我一個很好的解決方案,但是:

  • 我如何控制的名稱元素DictionaryItemOfInt32Foo
  • 如果我定義了Dictionary<FooInt32, Int32>和I,會發生什麼情況有類FooFooInt32
  • 可以優化上面的類嗎?

非常感謝!

回答

0

您可以在該類上設置[XmlElement(ElementName =「name」)]。雖然我沒有嘗試過,但可能必須將其設置在其他位置。無論如何,在某處設置ElementName是最好的選擇。

+0

如果指定任意名稱,則不能反序列化元素。 – Luca 2010-05-15 11:44:13

相關問題