序列化Dictionary <string,object =“”> </string,>

时间:2014-03-29 19:00:55

标签: c# serialization dictionary

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

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

2 个答案:

答案 0 :(得分:4)

您应该为课程Serializable添加Beam属性:

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

答案 1 :(得分:3)

您需要将Beam类标记为可序列化

[Serializable]
class Beam
{ ... }

http://msdn.microsoft.com/en-us/library/ms233843.aspx