gpt4 book ai didi

c# - 序列化字典

转载 作者:行者123 更新时间:2023-11-30 19:59:49 24 4
gpt4 key购买 nike

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

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

我如何序列化这个字典?当 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();
}

最佳答案

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

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

关于c# - 序列化字典<string, object>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22735492/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com