SurrogateSelector似乎只适用于根对象

时间:2013-01-17 12:32:03

标签: .net serialization binary-serialization

我尝试使用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),但是当反序列化包含字符串的对象(作为可serilizable成员)时,不会调用它。要序列化/反序列化的对象如下所示:

   [Serializable]
   class TestToSerialize
   {
       public string s1;
       public TestToSerialize()
       {
           s1 = "some test";
       }
   }

有没有办法在非根对象上调用代理? 为了完整性,Surrogate看起来像这样(仅用于设置断点的测试代码):

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;
    }
}

1 个答案:

答案 0 :(得分:-1)

肯定会在非root对象上调用代理 - 我经常在我自己的代码中使用它。

我认为String不适合用于测试。