我有一些序列化代码设置如下:
static void SerialiseObject(Object o, String path)
{
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream(path, FileMode.Create);
formatter.Serialize(stream, o);
stream.Close();
}
static Object DeserialiseObject(String path)
{
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream(path, FileMode.Open, FileAccess.Read);
Object o = (Object)formatter.Deserialize(stream);
stream.Close();
return o;
}
定义了以下成员的类:
[Serializable]
public class CircuitModel
{
public Dictionary<String, Bus> Buses { protected set; get; }
...
}
我填充了Dictionary,然后以下代码成功地序列化和反序列化了字典,所有Bus
个对象都保持不变:
SerialiseObject(CircuitModel.Buses, "temp.bin");
Object o = DeserialiseObject("temp.bin");
但是当我尝试为CircuitModel
做同样的事情时:
SerialiseObject(CircuitModel, "temp.bin");
Object o = DeserialiseObject("temp.bin");
CircuitModel.Buses
已初始化,但为空。
我也尝试使用ISerializable
实现序列化(对于Bus
和CircuitModel
类)并且遇到完全相同的问题
知道为什么会发生这种情况?
答案 0 :(得分:2)
我认为你的子集合中有一些更恶毒的东西,因为类中的字典的二进制序列化确实可以正常工作。
[TestFixture]
public class SerializeTest
{
[Test]
public void TestSer()
{
var parent = new Parent
{
Name = "Test"
};
parent.Children.Add("Child1", new Child {Name = "Child1"});
parent.Children.Add( "Child2", new Child { Name = "Child2" } );
SerialiseObject(parent, "test.bin");
var copy = DeserialiseObject("test.bin") as Parent;
Assert.IsNotNull(copy);
Assert.AreEqual(2, copy.Children.Count);
Assert.IsTrue(copy.Children.ContainsKey("Child1"));
Assert.AreEqual("Child1", copy.Children["Child1"].Name);
}
static void SerialiseObject( Object o, String path )
{
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream( path, FileMode.Create );
formatter.Serialize( stream, o );
stream.Close();
}
static Object DeserialiseObject( String path )
{
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream( path, FileMode.Open, FileAccess.Read );
Object o = (Object) formatter.Deserialize( stream );
stream.Close();
return o;
}
[Serializable]
private class Parent
{
public string Name { get; set; }
public Dictionary<string, Child> Children { get; protected set; }
public Parent()
{
Children = new Dictionary<string, Child>();
}
}
[Serializable]
private class Child
{
public string Name { get; set; }
}
}
子项与父项反序列化并包含它们初始化的详细信息。我会检查设置Buses
集合的任何代码。我的例子只是在父类的构造函数中做到了,但是在反序列化后你可能会设置流氓代码吗?
答案 1 :(得分:0)
字典不可序列化。如果需要序列化该数据,请删除该字典,并将其替换为包含字典中数据的自定义类的列表:
[Serializable]
public class BusItem
{
public string Name {get;set;}
public Bus Bus {get;set;}
}
编辑:我发现你实际上可以使用DataContractSerializer
来序列化字典。
http://theburningmonk.com/2010/05/net-tips-xml-serialize-or-deserialize-dictionary-in-csharp/
答案 2 :(得分:-1)
如果您正在讨论XML序列化,可能是因为Dictionary不能序列化为XML。请看Why isn't there an XML-serializable dictionary in .NET。