2012-08-14 138 views
2

我有一個名爲tileSet的序列化類,它包含一個字典(ushort,Tile)。所述字典中的Tile類也是可序列化的,並且其中包含字典(字符串,Rectangle [])。C#字典反序列化

問題是,當我去反序列化一個tileSet的實例時,儘管使用SerializationInfo.GetValue進行設置,但在tile的反序列化構造函數中,tile的字典(字符串,Rectangle [])仍然保留count = 0。 bizzare部分是,一旦我們離開Tile的反序列化構造器,並且tileSet被完全反序列化;我們看到Tile的字典(字符串,Rectangle [])現在已正確填充。

是否有人對此延遲有解釋? (下面淡化代碼)

地形設置反序列化:

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 
} 
+3

如果你能避免序列化的字典,就能爲您節省很多頭痛的道路。而是序列化一個KeyValuePairs數組,並在反序列化期間重新創建字典。 – Osiris 2012-08-14 16:04:01

+0

'mAnimations'是一個字段,一個非虛擬屬性還是一個虛擬屬性? – 2012-08-14 16:37:03

+0

@Osiris借調。字典序列化是雜亂無章的。列表或數組更容易處理。 – 2012-08-14 16:44:06

回答

0

您可以強制字典來執行它的OnDeserialization通過在ondeserialize方法/反序列化構造這樣做。

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