我有一个像这样的简单类:
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();
}
答案 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
{ ... }