0

我想要序列化字典集合,但我的代码有错误。我哪里错了?这是我的代码。

Dictionary<country,string> Countries=new Dictionary<country,string>();

Countries.Add(new country() { code = "AF", iso = 4 }, "Afghanistan");
Countries.Add(new country() { code = "AL", iso = 8 }, "Albania");
Countries.Add(new country() { code = "DZ", iso = 12 }, "Algeria");
Countries.Add(new country() { code = "AD", iso = 20 }, "Andorra");

FileStream fs = new FileStream("John1.xml", FileMode.Create);
XmlSerializer xs = new XmlSerializer(typeof(Dictionary<country, string>));
xs.Serialize(fs, Countries);

阶级国家

public class country
{
    public string code { get; set; }
    public int iso { get; set; }
}
4

2 回答 2

1

XmlSerializer 无法序列化字典,但您可以将字典转换为 KeyValue 对列表并对其进行序列化:

Dictionary<country,string> Countries=new Dictionary<country,string>();

Countries.Add(new country() { code = "AF", iso = 4 }, "Afghanistan");
Countries.Add(new country() { code = "AL", iso = 8 }, "Albania");
Countries.Add(new country() { code = "DZ", iso = 12 }, "Algeria");
Countries.Add(new country() { code = "AD", iso = 20 }, "Andorra");

FileStream fs = new FileStream("John1.xml", FileMode.Create);
XmlSerializer xs = new XmlSerializer(typeof(List<KeyValuePair<country, string>>));
xs.Serialize(fs, Countries.Select(x=>new KeyValuePair<country,string>(){ Key = x.Key, Value = x.Value}).ToList());

编辑:要考虑的另一件事:您不能使用System.Collections.Generic.KeyValuePair框架提供的结构,因为它不可序列化(键和值属性被标记为只读)。您必须编写自己的 KeyValue 结构:

[Serializable]
public struct KeyValuePair<K, V>
{
  public K Key { get; set; }    
  public V Value  { get; set; }
}
于 2013-10-15T12:36:57.680 回答
0

你可以DataContractSerializer选择。它可以序列化 .NET Dictionary

如何:使用 DataContractSerializer 进行序列化

于 2013-10-15T12:32:25.380 回答