序列化类

public class BinarySerialize
    {
        string strFile = "c:""book.data";

        public void Serialize(Book book)
        {
            using (FileStream fs = new FileStream(strFile, FileMode.Create))
            {
                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(fs, book);
            }
        }

        public Book DeSerialize()
        {
            Book book;
            using (FileStream fs = new FileStream(strFile, FileMode.Open))
            {
                BinaryFormatter formatter = new BinaryFormatter();
                book = (Book)formatter.Deserialize(fs);
            }
            return book;
        }
    }


----------------------------------------------------------------------------------

public class SoapSerialize
    {
        string strFile = "c:""book.soap";

        public void Serialize(Book book)
        {
            using (FileStream fs = new FileStream(strFile, FileMode.Create))
            {
                SoapFormatter formatter = new SoapFormatter();

                formatter.Serialize(fs, book);
            }
        }

        public Book DeSerialize()
        {
            Book book;
            using (FileStream fs = new FileStream(strFile, FileMode.Open))
            {
                SoapFormatter formatter = new SoapFormatter();
                book = (Book)formatter.Deserialize(fs);
            }
            return book;
        }
    }


---------------------------------------------------------------

 public class XmlSerialize
    {
        string strFile = "c:""book.xml";

        public void Serialize(Book book)
        {
            using (FileStream fs = new FileStream(strFile, FileMode.Create))
            {
                XmlSerializer formatter = new XmlSerializer(typeof(Book));
                formatter.Serialize(fs, book);
            }
        }

        public Book DeSerialize()
        {
            Book book;
            using (FileStream fs = new FileStream(strFile, FileMode.Open))
            {
                XmlSerializer formatter = new XmlSerializer(typeof(Book));
                book = (Book)formatter.Deserialize(fs);
            }
            return book;
        }
    }

采用xml序列化的方式只能保存public的字段和可读写的属性,对于private等类型的字段不能进行序列化
出现循环引用的情况,对于BinarySerialize和SoapSerialize可以正常序列化(.NET内部进行处理了),对于XmlSerialize出现这种情况会报错:"序列化类型 SerializableTest.Book 的对象时检测到循环引用。"

 

你可能感兴趣的:(C++,c,xml,C#,SOAP)