• .NET面试基础知识之序列化(Serialize)(四)


    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)

  • 相关阅读:
    Office2003中文绿色免安装版本(wordExcelPowerPoint三合一)
    图片去背景神奇网站remove.bg
    网络视频下载分享
    Windows10手机投屏到电脑
    测试开发工程必备技能之一:Mock的使用
    实战教程:如何将自己的Python包发布到PyPI上
    Sysbench测试神器:一条命令生成百万级测试数据
    Java 获取PDF中的数字签名信息
    Java 在Excel中添加分离型饼图、环形图
    C#/VB.NET 添加、删除PPT幻灯片中的数字签名
  • 原文地址:https://www.cnblogs.com/sift/p/3597465.html
Copyright © 2020-2023  润新知