How to do it...

  1. Start by adding an abstract class called Cat. This class simply defines fields for Weight and Age. Note that in order to make your class serializable, you need to add the [Serializable] attribute to it.
        [Serializable]
public abstract class Cat
{
// fields
public int Weight;
public int Age;
}
  1. Next, create a class called Tiger that is derived from the Cat class. Note that the Tiger class must also have the [Serializable] attribute added. This is because the serialization isn't inherited from the base class. Each derived class must implement serialization on its own:
        [Serializable]
public class Tiger : Cat
{
public string Trainer;
public bool IsTamed;
}
  1. Next, we need to create a method to serialize the Tiger class. Create a new object of type Tiger and set some values to it. We then use a BinaryFormatter to serialize the Tiger class into a stream and return it to the calling code:
        private static Stream SerializeTiger()
{
Tiger tiger = new Tiger();
tiger.Age = 12;
tiger.IsTamed = false;
tiger.Trainer = "Joe Soap";
tiger.Weight = 120;

MemoryStream stream = new MemoryStream();
BinaryFormatter fmt = new BinaryFormatter();
fmt.Serialize(stream, tiger);
stream.Position = 0;
return stream;
}
  1. Deserialization is even easier. We create a DeserializeTiger method and pass the stream to it. We then use the BinaryFormatter again to deserialize the stream into an object of type Tiger:
        private static void DeserializeTiger(Stream stream)
{
stream.Position = 0;
BinaryFormatter fmt = new BinaryFormatter();
Tiger tiger = (Tiger)fmt.Deserialize(stream);
}
  1. To see the results of our serialization and deserialization, read the result from the SerializeTiger() method into a new Stream and display it in the console window. Then, call the DeserializeTiger() method:
        Stream str = SerializeTiger();
WriteLine(new StreamReader(str).ReadToEnd());
DeserializeTiger(str);
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.140.204