Csharp/CSharp Tutorial/File Directory Stream/Serializable annotation

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Custom Serialization

using System.Runtime.Serialization.Formatters.Soap;
using System.IO;
using System;
using System.Collections.Generic;
using System.Text;
using System.Runtime.Serialization;
  [Serializable]
  class StringData : ISerializable
  {
    public string dataItemOne = "First";
    public string dataItemTwo= "data";
    public StringData() { }
    protected StringData(SerializationInfo si, StreamingContext ctx)
    {
      dataItemOne = si.GetString("First").ToLower();
      dataItemTwo = si.GetString("data").ToLower();
    }
    void ISerializable.GetObjectData(SerializationInfo info, StreamingContext ctx)
    {
      info.AddValue("First", dataItemOne.ToUpper());
      info.AddValue("data", dataItemTwo.ToUpper());
    }
  }
  [Serializable]
  class MoreData
  {
    public string dataItemOne = "block";
    public string dataItemTwo = "data";
    [OnSerializing]
    private void OnSerializing(StreamingContext context)
    {
      dataItemOne = dataItemOne.ToUpper();
      dataItemTwo = dataItemTwo.ToUpper();
    }
    [OnDeserialized]
    private void OnDeserialized(StreamingContext context)
    {
      dataItemOne = dataItemOne.ToLower();
      dataItemTwo = dataItemTwo.ToLower();
    }
  }
  class Program
  {
    static void Main(string[] args)
    {
      MoreData myData = new MoreData();
      SoapFormatter soapFormat = new SoapFormatter();
      using (Stream fStream = new FileStream("MyData.soap",FileMode.Create, FileAccess.Write, FileShare.None))
      {
        soapFormat.Serialize(fStream, myData);
      }
    }
  }

Serializable annotation

using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
class MainClass
{
  [STAThread]
  static void Main(string[] args)
  {
    Point p1 = new Point();
    p1.xpoint = 1;
    p1.ypoint = 2;
    Stream stream = File.Open("point.bin", FileMode.Create);
    BinaryFormatter bformatter = new BinaryFormatter();
    bformatter.Serialize(stream, p1);
    stream.Close();
    Stream openStream = File.Open("point.bin", FileMode.Open);
    Point desierializedPoint = new Point();
    desierializedPoint = (Point)bformatter.Deserialize(openStream);
  }
}
[Serializable()]
class Point
{
  public int xpoint;
  public int ypoint;
}

Serialize a list of objects

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

    class Program
    {
        static void Main(string[] args)
        {
            List<Product> products = new List<Product>();
            products.Add(new Product(1, "A", 10.0, "A."));
            products.Add(new Product(2, "B", 25.0, "B."));
            products.Add(new Product(4, "C", 12.0, "C."));
            IFormatter serializer = new BinaryFormatter();
            FileStream saveFile =new FileStream("Products.bin", FileMode.Create, FileAccess.Write);
            serializer.Serialize(saveFile, products);
            saveFile.Close();
            FileStream loadFile =new FileStream("Products.bin", FileMode.Open, FileAccess.Read);
            List<Product> savedProducts = serializer.Deserialize(loadFile) as List<Product>;
            loadFile.Close();
        }
    }
    [Serializable]
    public class Product
    {
        public long Id;
        public string Name;
        public double Price;
        [NonSerialized]
        string Notes;
        public Product(long id, string name, double price, string notes)
        {
            Id = id;
            Name = name;
            Price = price;
            Notes = notes;
        }
        public override string ToString()
        {
            return string.Format("{0}: {1} (${2:F2}) {3}", Id, Name, Price, Notes);
        }
    }

Serialize objects

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
    [Serializable]
    public class Person
    {
        public Person()
        {
        }
        public int Age { get; set; }
        public int WeightInPounds { get; set; }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Serialize();
            DeSerialize();
        }
        public static void Serialize()
        {
            Person me = new Person();
            me.Age = 40;
            me.WeightInPounds = 200;
            Stream s = File.Open("Me.dat", FileMode.Create);
            BinaryFormatter bf = new BinaryFormatter();
            bf.Serialize(s, me);
            s.Close();
        }
        public static void DeSerialize()
        {
            Stream s = File.Open("Me.dat", FileMode.Open);
            BinaryFormatter bf = new BinaryFormatter();
            object o = bf.Deserialize(s);
            Person p = o as Person;
            s.Close();
        }
    }