0
我嘗試使用SurrogatSelector來自定義流的反序列化。它適用於對象圖的根對象,但不適用於包含的對象。見下面的代碼:SurrogateSelector似乎只適用於根對象
Stream stream = File.Open("C:\\Temp\\test.bin", FileMode.Create);
BinaryFormatter formatter = new BinaryFormatter();
TestToSerialize tts = new TestToSerialize();
formatter.Serialize(stream, tts);
stream.Close();
stream = File.Open("C:\\Temp\\test.bin", FileMode.Open);
formatter = new BinaryFormatter();
SurrogateSelector ss = new SurrogateSelector();
ss.AddSurrogate(typeof(string), new StreamingContext(StreamingContextStates.All), new StringSerializationSurrogate());
formatter.SurrogateSelector = ss;
tts = (TestToSerialize)formatter.Deserialize(stream);
stream.Close();
的StringSerializationSurrogate被調用(方法SetObjectData)當一個字符串被反序列化,而不是在包含字符串(作爲serilizable構件)的對象被反序列化。要進行序列化對象/解串看起來是這樣的:
[Serializable]
class TestToSerialize
{
public string s1;
public TestToSerialize()
{
s1 = "some test";
}
}
有沒有辦法有代孕得到所謂非根對象? 爲完整的代孕看起來像這樣(只testcode設置斷點):
sealed class StringSerializationSurrogate : ISerializationSurrogate
{
public void GetObjectData(Object obj, SerializationInfo info, StreamingContext context)
{
}
public object SetObjectData(object obj, SerializationInfo info, StreamingContext context, ISurrogateSelector selector)
{
string s = (String)obj;
return obj;
}
}
嗨Lachlan,哪種類型工作,哪種類型應該用於測試? – Gerhard