C# 简单序列化与反序列化

        //序列化                                                
        public void Serialize(Book book)
        {

            using (FileStream fs = new FileStream(strFile, FileMode.Create))        //FileMode.Create打开或创建一个文件                                                
            {
                //以二进制格式将对象或整个连接对象图形序列化和反序列化。                                                
                BinaryFormatter formatter = new BinaryFormatter();
                //将Book对象图形序列化为给定流。                                                 
                formatter.Serialize(fs, book);
            }
        }



        //反序列化                                                
        public Book DeSerialize()
        {
            Book book;
            using (FileStream fs = new FileStream(strFile, FileMode.Open))
            {
                BinaryFormatter formatter = new BinaryFormatter();
                //将指定的流反序列化为book对象                                                
                book = (Book)formatter.Deserialize(fs);                            //执行此方法返回Object对象需要强转                    
            }
            return book;
        }                    

猜你喜欢

转载自www.cnblogs.com/YuanDong1314/p/8967960.html