C#自定义序列化 Formatter FormatterServices

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Reflection;
using System.Runtime.Serialization;
namespace FormatConverter
{
    class Program
    {
        static void Main(string[] args)
        {
            Rectangle.Serialize();
        }
    }
    [Serializable()]
    public class Rectangle : ISerializable, IDeserializationCallback
    {
        public double LengthRect;
        public double WidthRect;
        public SerializationInfo InfoSerial;
        public StreamingContext ContextStream;
        [NonSerialized()]
        public double AreaRect;
        public Rectangle(double length, double width)
        {
      
            this.LengthRect = length;
            this.WidthRect = width;
            this.AreaRect = this.LengthRect * this.WidthRect;
        }
        public Rectangle(SerializationInfo Info, StreamingContext context)
        {
            this.InfoSerial = Info;
            this.ContextStream = context;
        }
        public void OnDeserialization(object sender)
        {
            this.LengthRect = InfoSerial.GetDouble("LengthRect");
            this.WidthRect = InfoSerial.GetDouble("WidthRect");
            this.AreaRect = this.LengthRect * this.WidthRect;
            Console.WriteLine(" You are in OnDeserialization method");
        }
        public override string ToString()
        {
            return string.Format("Length={0},Width={1},Area={2}",this.LengthRect,this.WidthRect,this.AreaRect);
        }
        public void GetObjectData(SerializationInfo info, StreamingContext context)
        {
            MemberInfo[] memInfo = FormatterServices.GetSerializableMembers(this.GetType(),context);
            for (int i = 0; i < memInfo.Length; i++)
            {
                info.AddValue(memInfo[i].Name,((FieldInfo)(memInfo[i])).GetValue(this));
            }
        }
        public static void Serialize()
        {
            Rectangle c = new Rectangle(10,20);
            FileStream fs = new FileStream("E:\\DataFile.dat",FileMode.Create);
            CustomFormatter formatter = new CustomFormatter();
            formatter.Serialize(fs, c);
            fs.Close();
        }
        public static void Deserializa()
        {
            Rectangle c = null;
            FileStream fs = new FileStream("E:\\DataFile.dat",FileMode.Open);
            CustomFormatter formatter = new CustomFormatter();
            c = (Rectangle)formatter.Deserialize(fs);
            fs.Close();
        }
    }

    public class CustomFormatter : Formatter
    {
        public override object Deserialize(System.IO.Stream serializationStream)
        {
            StreamReader st = new StreamReader(serializationStream);
            string str = st.ReadToEnd();
            char[] temp = new char[] { char.Parse(",")};
            string[] s = str.Split(temp);
            SerializationInfo ss=new SerializationInfo(typeof(Rectangle),new CustomFormatterConverter());
            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 override void Serialize(Stream serializationStream, object graph)
        {
            Rectangle g = (Rectangle)graph;
            SerializationInfo ss = new SerializationInfo(typeof(Rectangle),new CustomFormatterConverter());
            if ((g) is ISerializable)
            {
                g.GetObjectData(ss, new StreamingContext());
            }
            CustomFormatterConverter ob = new CustomFormatterConverter();
            byte[] ba = (byte[])ob.Convert(ss, TypeCode.Byte);
            serializationStream.Write(ba, 0, ba.Length);
        }
        public override SerializationBinder Binder
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }
        public override StreamingContext Context
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }
        public override ISurrogateSelector SurrogateSelector
        {
            get
            {
                throw new NotImplementedException();
            }
            set
            {
                throw new NotImplementedException();
            }
        }
        protected override void WriteArray(object obj, string name, Type memberType)
        {
            throw new NotImplementedException();
        }
        protected override void WriteBoolean(bool val, string name)
        {
            throw new NotImplementedException();
        }
        protected override void WriteByte(byte val, string name)
        {
            throw new NotImplementedException();
        }
        protected override void WriteChar(char val, string name)
        {
            throw new NotImplementedException();
        }
        protected override void WriteDateTime(DateTime val, string name)
        {
            throw new NotImplementedException();
        }
        protected override void WriteDecimal(decimal val, string name)
        {
            throw new NotImplementedException();
        }
        protected override void WriteDouble(double val, string name)
        {
            throw new NotImplementedException();
        }
        protected override void WriteInt16(short val, string name)
        {
            throw new NotImplementedException();
        }
        protected override void WriteInt32(int val, string name)
        {
            throw new NotImplementedException();
        }
        protected override void WriteInt64(long val, string name)
        {
            throw new NotImplementedException();
        }
        protected override void WriteMember(string memberName, object data)
        {
            base.WriteMember(memberName, data);
        }
        protected override void WriteObjectRef(object obj, string name, Type memberType)
        {
            throw new NotImplementedException();
        }
        protected override void WriteSByte(sbyte val, string name)
        {
            throw new NotImplementedException();
        }
        protected override void WriteSingle(float val, string name)
        {
            throw new NotImplementedException();
        }
        protected override void WriteTimeSpan(TimeSpan val, string name)
        {
            throw new NotImplementedException();
        }
        protected override void WriteUInt16(ushort val, string name)
        {
            throw new NotImplementedException();
        }
        protected override void WriteUInt32(uint val, string name)
        {
            throw new NotImplementedException();
        }
        protected override void WriteUInt64(ulong val, string name)
        {
            throw new NotImplementedException();
        }
        protected override void WriteValueType(object obj, string name, Type memberType)
        {
            throw new NotImplementedException();
        }
    }
    class CustomFormatterConverter:FormatterConverter
    {
        public new object Convert(object value, TypeCode type)
        {
            byte[] ba = Encoding.ASCII.GetBytes(((SerializationInfo)(value)).GetDouble("LengthRect")+"," + ((SerializationInfo)(value)).GetDouble("LengthRect"));
            return ba;
        }
    }
}

 

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

导航