我想序列化,然後反序列化一個對象的類從Dictionary<string,int>
從字符串成員字段派生。使用ProtoBuf淨去派生類型(字典)deseriailize沒有正確設置對象字段
public class TempClass : Dictionary<string, int>
{
public string Version;
public TempClass() { }
}
我寫一個單元測試,以捕獲我運行到該問題:所述構件字段未設置時或者串行化或反串行化(到/從一個字節[])與protobuf網。驗證已反序列化的Version
已正確設置時,此測試在最後的Assert
中失敗。它始終設置爲null
而不是正確的"someVersion"
。
[TestClass]
public class serializationTest
{
[TestMethod]
public void TestMethod1()
{
string newVersion = "someVersion";
TempClass original = new TempClass()
{
{"a", 2},
{"b", 3},
{"c", 1},
};
original.Version = newVersion;
byte[] serialized = Serialize(original);
TempClass deserialized = Deserialize(serialized);
// Validate
foreach (var pair in original)
{
Assert.IsTrue(deserialized.ContainsKey(pair.Key));
Assert.AreEqual(pair.Value, deserialized[pair.Key]);
}
Assert.AreEqual(newVersion, original.Version, "original mapping version not set correctly");
Assert.AreEqual(newVersion, deserialized.Version, "deserialized version doesn't match");
}
private static TempClass Deserialize(byte[] serialized)
{
TempClass deserialized;
using (MemoryStream ms = new MemoryStream())
{
ms.Write(serialized, 0, serialized.Length);
ms.Position = 0;
deserialized = Serializer.Deserialize<TempClass>(ms);
}
return deserialized;
}
private static byte[] Serialize(TempClass mapping)
{
byte[] serialized;
using (MemoryStream ms = new MemoryStream())
{
Serializer.Serialize(ms, mapping);
serialized = ms.ToArray();
}
return serialized;
}
}
我已經嘗試與BinaryFormatter
,也是DataContractSerializer
同樣的工作都無濟於事。有人可以幫我找出導致此測試失敗的原因嗎?
的後續問題:相反,如果我重新定義了TempClass
這樣,構造函數總是被調用,而不是正確地設置成員字段原來的Version
。我如何反序列化沒有構造函數創建一個新的Version
,而只是複製原始的?
public class TempClass : Dictionary<string, int>
{
public string Version;
public TempClass()
{
Version = DateTime.UtcNow.ToString("s");
}
}
感謝您輕鬆使用測試。這節省了時間。 – gabba 2014-10-08 17:20:38