【发布时间】:2014-03-29 19:00:54
【问题描述】:
我有一个像这样的简单类:
class Beam
{
public string Name { get; set; }
public double Width { get; set; }
public double Height { get; set; }
}
我将它用作Dictionary 中的值:
var addresses = new Dictionary<string, Beam>
{
{"Beam1", new Beam{Name = "B1", Width = 10, Height = 10}},
{"Beam2", new Beam{Name = "B2", Width = 5, Height = 5}}
};
我怎样才能Serialize 这个Dictionary?当Dictionary 如下所示时,我可以做到:
Dictionary<string, string>
但是当我使用 Object 作为它的值时,我遇到了一个异常。
更新
var fs = new FileStream("DataFile.dat", FileMode.Create);
// Construct a BinaryFormatter and use it to serialize the data to the stream.
var formatter = new BinaryFormatter();
try
{
formatter.Serialize(fs, addresses);
}
catch (SerializationException e)
{
Console.WriteLine("Failed to serialize. Reason: " + e.Message);
throw;
}
finally
{
fs.Close();
}
【问题讨论】:
标签: c# serialization dictionary