【发布时间】:2013-08-02 17:20:54
【问题描述】:
我有一个名为 tileSet 的可序列化类,其中包含一个字典(ushort,Tile)。上述字典中的 Tile 类也是可序列化的,其中包含一个字典(string,Rectangle[])。
问题是当我去反序列化一个 tileSet 的实例时,而在 Tile 的反序列化构造函数中,尽管使用 SerializationInfo.GetValue 设置了 tile 的字典(字符串,矩形 []),但仍保持 count=0。
奇怪的是,一旦我们离开了 Tile 的反序列化构造函数,tileSet 就完全反序列化了;我们看到 Tile 的 dictionary(string,Rectangle[]) 现在已正确填充。
有人对这种延迟有解释吗? (下面的淡化代码)
TileSet 反序列化:
Stream stream = File.Open(path, FileMode.Open);
BinaryFormatter bFormatter = new BinaryFormatter();
// The following line will place us in Tile's
// Deserialization constructor below
TileSet tileSet = (TileSet)bFormatter.Deserialize(stream);
// If debugging, by this point tileSet's, Tile's dictionary is
// now properly set with a count of 0.
stream.Close();
Tile 反序列化构造函数:
//Deserialization Constructor
public Tile(SerializationInfo info, StreamingContext sContext)
{
mAnimations = (Dictionary<string, Rectangle[]>)
info.GetValue("animations",
typeof(Dictionary<string, Rectangle[]>));
mPaused = false;
mName = (string)info.GetValue("name", typeof(string));
mWalkable = (bool)info.GetValue("walkable", typeof(bool));
mInstanced = (bool)info.GetValue("instanced", typeof(bool));
setCurrentState((string)info.GetValue("currentState", typeof(string)));
//By this point mAnimations is not properly set but has a count=0
}
【问题讨论】:
-
如果您可以避免对字典进行序列化,那么您将在以后省去很多麻烦。而是序列化一个 KeyValuePairs 数组并在反序列化期间重新创建字典。
-
mAnimations是字段、非虚拟属性还是虚拟属性? -
@Osiris 附议。字典序列化是随意的。列表或数组更容易使用。
-
嗯。字典的序列化代码也是如此。除非我必须保证将来与序列化兼容,否则我会序列化字典,直到它确实引起问题,然后编写十几行代码来更改它。
-
看来我忽略了 onDeserialization() 方法。但是,我切换到序列化为列表。
标签: c# serialization xna