我尝试使用 SurrogatSelector 来自定义流的反序列化。它适用于对象图的根对象,但不适用于包含的对象。请参阅以下代码:
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),但在反序列化包含字符串(作为可序列化成员)的对象时不调用。要序列化/反序列化的对象如下所示:
[Serializable]
class TestToSerialize
{
public string s1;
public TestToSerialize()
{
s1 = "some test";
}
}
有没有办法让代理在非根对象上被调用?为了完整起见,代理看起来像这样(测试代码仅用于设置断点):
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;
}
}