C# C字典反序列化

C# C字典反序列化,c#,serialization,xna,C#,Serialization,Xna,我有一个名为tileSet的可序列化类,它包含DictionarySort,Tile。所述字典中的Tile类也是可序列化的,并且包含一个dictionarystring,矩形[] 问题是,当我去反序列化tileSet的实例时,在Tile的反序列化构造函数中,尽管使用SerializationInfo.GetValue进行了设置,但Tile的dictionarystring矩形[]仍保留count=0 奇怪的是,一旦我们离开Tile的反序列化构造函数,tileSet就完全反序列化了;我们看到平铺的

我有一个名为tileSet的可序列化类,它包含DictionarySort,Tile。所述字典中的Tile类也是可序列化的,并且包含一个dictionarystring,矩形[]

问题是,当我去反序列化tileSet的实例时,在Tile的反序列化构造函数中,尽管使用SerializationInfo.GetValue进行了设置,但Tile的dictionarystring矩形[]仍保留count=0

奇怪的是,一旦我们离开Tile的反序列化构造函数,tileSet就完全反序列化了;我们看到平铺的dictionarystring矩形[]现在已正确填充

有人对这次延误有什么解释吗?下面是淡化代码

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();
平铺反序列化构造函数:

//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);

通过在ondeserialize方法/反序列化构造函数中执行此操作,可以强制字典执行其OnDeserialization

mAnimations = (Dictionary<string, Rectangle[]>)  
    info.GetValue("animations",
        typeof(Dictionary<string, Rectangle[]>));  
mAnimations.OnDeserialize(this);

如果你能避免把字典连载,你会省去很多后顾之忧。相反,序列化KeyValuePairs数组并在反序列化过程中重新创建字典。操作是字段、非虚拟属性还是虚拟属性?@Osiris seconded。字典序列化是随意的。使用列表或数组要容易得多。Meh。字典的序列化代码也做得差不多。除非我承诺将来会向后兼容序列化,否则我会序列化字典,直到它真的引起问题,然后写十几行代码来修改它。看起来我忽略了序列化方法。不过,我改成了以列表的形式进行序列化。如果你能避免对字典进行序列化,那么今后你会省去很多麻烦。相反,序列化KeyValuePairs数组并在反序列化过程中重新创建字典。操作是字段、非虚拟属性还是虚拟属性?@Osiris seconded。字典序列化是随意的。使用列表或数组要容易得多。Meh。字典的序列化代码也做得差不多。除非我承诺将来会向后兼容序列化,否则我会序列化字典,直到它真的引起问题,然后写十几行代码来修改它。看起来我忽略了序列化方法。然而,我转而将其序列化为列表。