Serialize a Dictionary<string, object>

本文关键字:object gt string lt Dictionary Serialize | 更新日期: 2023-09-27 17:54:45

我有一个像这样的简单类:

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();
}

Serialize a Dictionary<string, object>

您应该为类Beam:

添加Serializable属性
[Serializable]
class Beam
{
    public string Name { get; set; }
    public double Width { get; set; }
    public double Height { get; set; }
}

您需要将Beam类标记为serializable

[Serializable]
class Beam
{ ... }
http://msdn.microsoft.com/en-us/library/ms233843.aspx