我有一个名为 tileSet 的可序列化类,它包含一个字典(ushort,Tile)。所述字典中的 Tile 类也是可序列化的,并且其中包含一个字典(string,Rectangle[])。
问题是当我去反序列化 tileSet 的一个实例时,在 Tile 的反序列化构造函数中,尽管使用 SerializationInfo.GetValue 设置了 tile 的字典(string,Rectangle[])仍然是 count=0。
奇怪的是,一旦我们离开了 Tile 的反序列化构造函数,tileSet 就被完全反序列化了;我们看到 Tile 的字典 (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
}
最佳答案
您可以通过在 ondeserialize 方法/反序列化构造函数中执行此操作来强制字典执行它的 OnDeserialization。
mAnimations = (Dictionary<string, Rectangle[]>)
info.GetValue("animations",
typeof(Dictionary<string, Rectangle[]>));
mAnimations.OnDeserialize(this);
关于C# 字典反序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11955482/