我有一个像这样的简单课程:
class Beam
{
public string Name { get; set; }
public double Width { get; set; }
public double Height { get; set; }
}
我将它用作 a 中的值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
this Dictionary
?我能够做到的时候Dictionary
就像下面这样:
Dictionary<string, string>
但是当我使用Object
作为它的价值我得到了一个例外。
Update
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();
}