Page 158 - CSharp/C#
P. 158

item.Name = (string)info.GetValue("_name", typeof(string));
                     return item;
                 }
             }

             class Program
             {
                 static void Main(string[] args)
                 {
                     var item = new Item
                     {
                         Name = "Orange"
                     };

                     var bytes = SerializeData(item);
                     var deserializedData = (Item)DeserializeData(bytes);
                 }

                 private static byte[] SerializeData(object obj)
                 {
                     var surrogateSelector = new SurrogateSelector();
                     surrogateSelector.AddSurrogate(typeof(Item), new
         StreamingContext(StreamingContextStates.All), new ItemSurrogate());

                     var binaryFormatter = new BinaryFormatter
                     {
                         SurrogateSelector = surrogateSelector
                     };

                     using (var memoryStream = new MemoryStream())
                     {
                         binaryFormatter.Serialize(memoryStream, obj);
                         return memoryStream.ToArray();
                     }
                 }

                 private static object DeserializeData(byte[] bytes)
                 {
                     var surrogateSelector = new SurrogateSelector();
                     surrogateSelector.AddSurrogate(typeof(Item), new
         StreamingContext(StreamingContextStates.All), new ItemSurrogate());

                     var binaryFormatter = new BinaryFormatter
                     {
                         SurrogateSelector = surrogateSelector
                     };

                     using (var memoryStream = new MemoryStream(bytes))
                         return binaryFormatter.Deserialize(memoryStream);
                 }
             }
         }


        Serialization Binder


        The binder gives you an opportunity to inspect what types are being loaded in your application
        domain


        Create a class inherited from SerializationBinder



        https://riptutorial.com/                                                                             104
   153   154   155   156   157   158   159   160   161   162   163