zoukankan      html  css  js  c++  java
  • .NET面试基础知识之序列化(Serialize)(三)

    Serializing a Type as a different type and deserializing an object as a different object

    下面的代码是序列化一个Singleton类并反序列化

      [Serializable]
        public sealed class SingletonSerializable:ISerializable
        {
            private SingletonSerializable()
            {
            }

            private static readonly SingletonSerializable theOneObject=new SingletonSerializable();

            public string Name="Jeff";
            public DateTime Date = DateTime.Now;

            public static SingletonSerializable GetSingleton()
            {
                return theOneObject;
            }

            [SecurityPermission(SecurityAction.Demand, SerializationFormatter = true)]
            void ISerializable.GetObjectData(SerializationInfo info, StreamingContext context)
            {
                info.SetType(typeof(SingletonSerializationHelper));

           //Tell the formatter to serialize the SingletonSerializable object as a SingletonSerializableHelper object instead.

          //The formatter automatically detected that both array elements refer to a single object, the formatter serialize only one object.

          //So the formatter no need the special constructor
            }

            [Serializable]

         //When a type implements IObjectReference, the formatter calls the GetRealObject method
            private sealed class SingletonSerializationHelper:IObjectReference
            {
                public Object GetRealObject(StreamingContext context)
                {
                    return SingletonSerializable.GetSingleton();

              //Return a reference to the object that you really want a reference to now that deserialization of the object has completed.
                }
            }
        }

    test

      public static void TestSingleton()
        {
            SingletonSerializable[] al = { SingletonSerializable.GetSingleton(),SingletonSerializable.GetSingleton()};
            Console.WriteLine("Do both elements refer to the same object?"+(al[0]==al[1]));//True

            using (Stream st = new MemoryStream()) {
               BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(st,al);
                st.Position = 0;
                SingletonSerializable[] a2 =(SingletonSerializable[]) formatter.Deserialize(st);
                Console.WriteLine("Do both elements refer to the same object?"+(a2[0]==a2[1]));//True
                Console.WriteLine("Do both elements refer to the same object?"+(al[0]==a2[0]));//True
            }
        }

  • 相关阅读:
    门面模式简述
    转:日志组件logback的介绍及配置使用方法
    spring boot项目中使用sfl4j+logbak配置
    druid相关资料
    spring boot +druid数据库连接池配置
    设计模式之Strategy模式
    转:高效代码审查的八条准则和十个经验
    SpringMVC如何解决POST请求中文乱码问题,GET的又如何处理呢?
    【其它】关于本博客的一些说明
    [THUWC2020] 自爆记
  • 原文地址:https://www.cnblogs.com/sift/p/3597376.html
Copyright © 2011-2022 走看看