【发布时间】:2010-05-14 21:50:41
【问题描述】:
我正在研究 XML 序列化,因为我使用了很多字典,所以我也想对它们进行序列化。我为此找到了以下解决方案(我为此感到非常自豪!:))。
[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>并且我有Foo和FooInt32类会发生什么? - 上面的类可以优化吗?
非常感谢!
【问题讨论】:
标签: c# serialization xml-serialization