C#自定义序列化

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Serialization;
using System.Runtime.Serialization;
using System.Xml;
namespace CustomFormatSerialization
{
    class Program
    {
        static void Main(string[] args)
        {
            Rectangle.Deserialize();
            Console.ReadKey();
        }
    }
    [Serializable()]
    public class Rectangle : ISerializable, IDeserializationCallback
    {
        public double LengthRect;
        public double WidthRect;
        [NonSerialized()]
        public double AreaRect;
        public SerializationInfo _InfoSerial;
        public StreamingContext _ContexStream;
        public Rectangle(double length, double width)
        {
            LengthRect = length;
            WidthRect = width;
            AreaRect = this.LengthRect * this.WidthRect;
        }
        public Rectangle(SerializationInfo info, StreamingContext context)
        {
            this._InfoSerial = info;
            this._ContexStream = context;
        }
        /// <summary>
        /// 完成反序列化的通知
        /// </summary>
        /// <param name="sender"></param>
        public void OnDeserialization(object sender)
        {
            this.LengthRect = this._InfoSerial.GetDouble("LengthRect");
            this.WidthRect = this._InfoSerial.GetDouble("WidthRect");
            this.AreaRect = this.LengthRect * this.WidthRect;
            Console.WriteLine("You are in OnDeserialization method");
        }
        public override string ToString()
        {
            return string.Format("Lenth={0},Width={1},Area={2}", LengthRect, WidthRect, AreaRect);
        }
        public void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            info.AddValue("LengthRect", this.LengthRect);
            info.AddValue("WidthRect", this.WidthRect);
        }
        public static void Serialize()
        {
            Rectangle c = new Rectangle(10, 20);
            FileStream fs = new FileStream("E:\\DataFile.dat", FileMode.Create);
            CustomFormatter formatter = new CustomFormatter();
            try
            {
                formatter.Serialize(fs, c);
            }
            catch
            {
                throw;
            }
            finally
            {
                fs.Close();
            }
        }
        public static void Deserialize()
        {
            Rectangle c = null;
            FileStream fs = new FileStream("E:\\DataFile.dat",FileMode.Open);
            try
            {
                CustomFormatter formatter = new CustomFormatter();
                c = ((Rectangle)(formatter.Deserialize(fs)));
                Console.WriteLine(c.ToString());
            }
            catch (SerializationException e)
            {
                Console.WriteLine(e.Message);
                throw;
            }
            finally
            {
                fs.Close();
            }
        }
    }

    public class CustomFormatter : IFormatter, IFormatterConverter
    {
        public SerializationBinder Binder
        {
            get { throw new NotSupportedException(); }
            set { throw new NotSupportedException(); }
        }
        public StreamingContext Context
        {
            get { throw new NotSupportedException(); }
            set { throw new NotSupportedException(); }
        }
        public ISurrogateSelector SurrogateSelector
        {
            get { throw new NotSupportedException(); }
            set { throw new NotSupportedException(); }
        }
        public object Deserialize(Stream serializationStream)
        {
            StreamReader sr = new StreamReader(serializationStream);
            string str = sr.ReadToEnd();
            char[] temp = new char[] { char.Parse(",") };
            string[] s = str.Split(temp);
            SerializationInfo ss = new SerializationInfo(typeof(Rectangle), new CustomFormatter());
            ss.AddValue("LengthRect", double.Parse(s[0]));
            ss.AddValue("WidthRect", double.Parse(s[1]));
            Rectangle ob = new Rectangle(ss, new StreamingContext());
            if ((ob) is IDeserializationCallback)
            {
                ob.OnDeserialization(ob);
            }
            return ob;
        }
        public void Serialize(Stream serializationStream, object graph)
        {
            Rectangle g = (Rectangle)(graph);
            SerializationInfo ss = new SerializationInfo(typeof(Rectangle), new CustomFormatter());
            if ((g) is ISerializable)
            {
                g.GetObjectData(ss, new StreamingContext());
            }
            byte[] ba = (byte[])this.Convert(ss, System.TypeCode.Byte);
            serializationStream.Write(ba, 0, ba.Length);

        }
        public object Convert(object value, System.TypeCode typeCode)
        {
            byte[] ba = Encoding.ASCII.GetBytes(((SerializationInfo)(value)).GetDouble("LengthRect") + "," + ((SerializationInfo)(value)).GetDouble("WidthRect"));
            return ba;
        }


        public object Convert(object value, Type typeCode)
        {
            byte[] ba = Encoding.ASCII.GetBytes(((SerializationInfo)(value)).GetDouble("LengthRect") + "," + ((SerializationInfo)(value)).GetDouble("WidthRect"));
            return ba;
        }


        public bool ToBoolean(object value)
        {
            throw new NotSupportedException();
        }

        public byte ToByte(object value)
        {
            throw new NotSupportedException();
        }

        public char ToChar(object value) { throw new NotSupportedException(); }

        public DateTime ToDateTime(object value) { throw new NotSupportedException(); }

        public decimal ToDecimal(object value) { throw new NotSupportedException(); }

        public double ToDouble(object value) { throw new NotSupportedException(); }

        public short ToInt16(object value) { throw new NotSupportedException(); }

        public int ToInt32(object value) { throw new NotSupportedException(); }

        public long ToInt64(object value) { throw new NotSupportedException(); }

        public sbyte ToSByte(object value) { throw new NotSupportedException(); }

        public float ToSingle(object value) { throw new NotSupportedException(); }

        public string ToString(object value) { throw new NotSupportedException(); }

        public ushort ToUInt16(object value) { throw new NotSupportedException(); }

        public uint ToUInt32(object value) { throw new NotSupportedException(); }

        public ulong ToUInt64(object value) { throw new NotSupportedException(); }
    }
}

 

posted on 2012-12-12 21:32  R.Ray  阅读(523)  评论(0)    收藏  举报

导航