序列化字典<字符串,对象>

2024-02-24

我有一个像这样的简单课程:

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

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

[Serializable]
class Beam
{
    public string Name { get; set; }
    public double Width { get; set; }
    public double Height { get; set; }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

序列化字典<字符串,对象> 的相关文章

随机推荐