【问题标题】:SurrogateSelector seems to work only on the root objectSurrogateSelector 似乎仅适用于根对象
【发布时间】:2013-01-17 12:32:03
【问题描述】:

我尝试使用 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;
    }
}

【问题讨论】:

    标签: .net serialization binary-serialization


    【解决方案1】:

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

    我认为 String 不是用于测试的好类型。

    【讨论】:

    • 嗨,Lachlan,哪种类型有效,我应该使用哪种类型进行测试?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-05
    • 1970-01-01
    • 1970-01-01
    • 2018-07-06
    • 2020-04-04
    • 2023-04-06
    • 2017-08-01
    相关资源
    最近更新 更多