C# 字典反序列化

标签 c# serialization xna

我有一个名为 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/

相关文章:

c# - 通过序列化 DataContract 将对象字段分离到两个文件中

c# - XNA - Farseer 物理 3.5 - 碰撞检测问题 - 无/零重力 - 太空游戏

c# - Xna调试

java - Avro:序列化/反序列化包含 Enum 值的文件时出现 ClassCastException

c# - 我如何在 NHibernate 中执行反向 LIKE 查询?

c# - ASP.NET 存储交叉请求数据

c# - 无法解决代码级别统一的 "SQL_Latin1_General_CP1_CI_AI"和 "Latin1_General_CI_AI"之间的排序规则冲突

Java - 从文件中读取松散结构的数据

c# - 从 Java 到 C# : storing couple of int using Dimension

c# - 无法在存储库构造函数中创建服务范围 asp.net core