【问题标题】:Serialize a Dictionary<string, object>序列化字典<string, object>
【发布时间】: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


    【解决方案1】:

    你应该为Beam类添加Serializable属性:

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

    【讨论】:

    • 向类添加属性不会影响性能,但在这种情况下,使用反射执行的序列化。如果您有任何性能问题,请通过实现ISerializable 接口来创建自己的序列化器/反序列化器。
    • 如果我有两个字典怎么办?我可以将这两个序列化为一个文件吗?我将其作为一个新问题提出。
    • 是的。您可以创建一个 container 类(带有Serializable 属性),包含这两个Dictionarys,或者创建自己的序列化程序。
    • 非常感谢。您能否在此处发布此内容以供其他可能遇到此问题的人参考。stackoverflow.com/questions/22735746/…
    【解决方案2】:

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

    [Serializable]
    class Beam
    { ... }
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-11-02
      • 2011-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-02
      • 1970-01-01
      相关资源
      最近更新 更多