首页 > Web开发 > 详细

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

时间:2014-03-12 22:43:43      阅读:569      评论:0      收藏:0      [点我收藏+]

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

.NET面试基础知识之序列化(Serialize)(三),布布扣,bubuko.com

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

原文:http://www.cnblogs.com/sift/p/3597376.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!