Page 156 - CSharp/C#
P. 156

public string Name
             {
                 get { return _name; }
                 set { _name = value; }
             }

             public Item ()
             {

             }

             protected Item (SerializationInfo info, StreamingContext context)
             {
                 _name = (string)info.GetValue("_name", typeof(string));
             }

             public void GetObjectData(SerializationInfo info, StreamingContext context)
             {
                 info.AddValue("_name", _name, typeof(string));
             }
         }


        For data serialization, you can specify the desired name and the desired type


         info.AddValue("_name", _name, typeof(string));


        When the data is deserialized, you will be able to read the desired type


         _name = (string)info.GetValue("_name", typeof(string));



        Serialization surrogates (Implementing ISerializationSurrogate)


        Implements a serialization surrogate selector that allows one object to perform serialization and
        deserialization of another

        As well allows to properly serialize or deserialize a class that is not itself serializable


        Implement ISerializationSurrogate interface


         public class ItemSurrogate : ISerializationSurrogate
         {
             public void GetObjectData(object obj, SerializationInfo info, StreamingContext context)
             {
                 var item = (Item)obj;
                 info.AddValue("_name", item.Name);
             }

             public object SetObjectData(object obj, SerializationInfo info, StreamingContext context,
         ISurrogateSelector selector)
             {
                 var item = (Item)obj;
                 item.Name = (string)info.GetValue("_name", typeof(string));
                 return item;
             }
         }




        https://riptutorial.com/                                                                             102
   151   152   153   154   155   156   157   158   159   160   161