我有以下類:如何序列化包含字典的類?
[Serializable]
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
public Dictionary<string, string> Attributes { get; set; }
}
我想使用XmlSerializer的序列化,並得到下面的輸出:
<Person>
<FirstName>John</FirstName>
<LastName>Doe</LastName>
<Attributes>
<PhoneNumber>12345</PhoneNumber>
<StreetName>...</StreetName>
<StreetNumber>...</StreetNumber>
...
</Attributes>
</Person>
任何幫助,將不勝感激。
/// <summary>
/// Save all information needed set current game state into given file.
/// </summary>
/// <param name="fileName"></param>
public void save(string fileName)
{
Dictionary<string, string> attributes = new Dictionary<string, string>();
attributes.Add("blue", "very");
attributes.Add("red", "not");
Stream stream = File.Open(fileName, FileMode.Create);
BinaryFormatter bFormatter = new BinaryFormatter();
// Request the current state of all registered
// objects and save them into the file.
foreach (KeyValuePair<string, string> storeOnDisk in attributes)
bFormatter.Serialize(stream, storeOnDisk);
stream.Close();
}
只需更換你的宣言詞典 - > SerializableDictionary。它將被自動序列化/反序列化 – skaeff 2010-11-11 12:41:54