NonSerialized attributes

image_pdfimage_print


   
 

    using System;
  using System.IO;
  using System.Runtime.Serialization.Formatters.Binary;
  using System.Runtime.Serialization.Formatters.Soap;
  

    public class RoomApp
    {
    public static void Main()
    {
      // Make a room and listen to the tunes.
      Console.WriteLine("Made a My Room...");
      MyRoom myAuto = new MyRoom("My", 50, false, true);
      myAuto.TurnOnRadio(true);
      myAuto.GoUnderWater();

      // Now save this room to a binary stream.
      FileStream myStream = File.Create("RoomData.dat");
      BinaryFormatter myBinaryFormat = new BinaryFormatter();
      myBinaryFormat.Serialize(myStream, myAuto);
      myStream.Close();
      Console.WriteLine("Saved room to roomdata.dat.");

      // Read in the Room from the binary stream.
      Console.WriteLine("Reading room from binary file.");
      myStream = File.OpenRead("RoomData.dat");
      MyRoom roomFromDisk = (MyRoom)myBinaryFormat.Deserialize(myStream);
      Console.WriteLine(roomFromDisk.PetName + " is alive!");
      roomFromDisk.TurnOnRadio(true);
      myStream.Close();
      
    }
    }  
  
  
  [Serializable]
    public class Radio
    {
    [NonSerialized]
    private int objectIDNumber = 9;

        public Radio(){}
    public void On(bool state)
    {
      if(state == true)
        Console.WriteLine("Music is on...");
      else
        Console.WriteLine("No tunes...");        
    }
    }


  [Serializable]
    public class Room
    {
    protected string petName;
    protected int maxInternetSpeed;
    protected Radio theRadio = new Radio();

        public Room(string petName, int maxInternetSpeed)
        {
      this.petName = petName;
      this.maxInternetSpeed = maxInternetSpeed;
        }
    public Room() {}

    public String PetName
    {
      get { return petName; }
      set { petName = value; }
    }
    public int MaxInternetSpeed
    {
      get { return maxInternetSpeed; }
      set { maxInternetSpeed = value; }
    }

    public void TurnOnRadio(bool state)
    {
      theRadio.On(state);
    }
    }


  [Serializable]
    public class MyRoom : Room
    {
    protected bool isFlightWorthy;
    protected bool isSeaWorthy;

    public MyRoom(string petName, int maxInternetSpeed, 
              bool canFly, bool canSubmerge)
      : base(petName, maxInternetSpeed)
        {
      this.isFlightWorthy = canFly;
      this.isSeaWorthy = canSubmerge;
    }
    public MyRoom(){}

    public void Fly()
    {
      if(isFlightWorthy)
        Console.WriteLine("Taking off!");
      else
        Console.WriteLine("Falling off cliff!");
    }

    public void GoUnderWater()
    {
      if(isSeaWorthy)
        Console.WriteLine("Diving....");
      else
        Console.WriteLine("Drowning!!!");      
    }
    }
    

           
         
     


This entry was posted in File Stream. Bookmark the permalink.