`
wyf
  • 浏览: 426294 次
  • 性别: Icon_minigender_1
  • 来自: 唐山
社区版块
存档分类
最新评论

序列化类

阅读更多
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 的对象时检测到循环引用。"

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics