Serialization Surrogate

一个对象去系列化另一个对象

Code:

  public sealed class UniversalToLocalTimeSerializationSurrogate:ISerializationSurrogate
    {
        public UniversalToLocalTimeSerializationSurrogate()
        {
        }

        public void GetObjectData(object obj,SerializationInfo info,StreamingContext context)
        {
            info.AddValue("Date",((DateTime)obj).ToUniversalTime().ToString("u"));
        }

        public object SetObjectData(object obj, SerializationInfo info, StreamingContext context,ISurrogateSelector selector)
        {
            return DateTime.ParseExact(info.GetString("Date"),"u",null).ToLocalTime();
        }
    }

实现ISerializationSurrogate接口

使用

    public static void TestSurrogate()
        {
            using (var st = new MemoryStream()) {
                IFormatter formatter = new SoapFormatter();
                SurrogateSelector ss = new SurrogateSelector();
                ss.AddSurrogate(typeof(DateTime),formatter.Context,
                    new UniversalToLocalTimeSerializationSurrogate());
                formatter.SurrogateSelector = ss;
                DateTime localTimeBeforeSerialize = DateTime.Now;
                formatter.Serialize(st, localTimeBeforeSerialize);

                st.Position = 0;
                Console.WriteLine(new StreamReader(st));

                st.Position = 0;
                DateTime localTimeAfterSerialize = (DateTime)formatter.Deserialize(st);

                Console.WriteLine("LocalTimeBeforeSerialize={0}",localTimeBeforeSerialize);
                Console.WriteLine("LocalTimeAfterSerialize={0}",localTimeAfterSerialize);
            }
        }

Surrogate selector可以是一个集合

实现接口ISurrogateSelector,有三个方法

void ChainSelector(ISurrogateSelector selector)

ISurrogateSelector GetNextSelector()

ISerializationSurrogate GetSurrogate(Type type, StreamContext context, out ISurrogateSelector selector)

posted on 2014-03-12 22:24  carolinehan  阅读(379)  评论(0编辑  收藏  举报