首页 > Windows开发 > 详细

C#之序列化对象(二进制方式序列化对象)

时间:2017-04-25 23:08:33      阅读:241      评论:0      收藏:0      [点我收藏+]

应用程序有时需要以对象的形式在磁盘上存储数据,FrameWork有两个可用的实现方式:

一:System.Runtime.Serialization.Formatters.Binarry这个名称空间包含了BinarryFormatter类,它能把对象序列化为二进制数据,把二进制数据序列化为对象

二:System.Runtime.Serialization.Formatters.Soap:这个名称空间中包含了类SoapFormat类,它能把对象序列化为Soap格式的XML数据

以上两个类都实现了IFormatter接口,IFormatter接口提供了下面两个方法:

技术分享

BinaryFormatter序列化、反序列化对象

[Serializable]
    class Test
    {
        public long Id;
        public string Name;
        public double Price;

        [NonSerialized]
        string Notes;

        public Test(long id, string name, double price, string notes)
        {
            this.Id = id;
            this.Name = name;
            this.Price = price;
            this.Notes = notes;
        }

        public override string ToString()
        {
            return string.Format("{0}:{1}  (${2:F2}) {3}", Id, Name, Price, Notes);
        }
static void Main(string[] args)
        {
            List<Test> tests = new List<Test>();
            tests.Add(new Test(1, "苹果", 5.5, "烟台红富士"));
            tests.Add(new Test(2, "菠萝", 3.5, "海南菠萝"));
            tests.Add(new Test(3, "樱桃", 100, "智利樱桃"));

            //用于序列化和反序列化的对象
            IFormatter serializer = new BinaryFormatter();

            //开始序列化
            FileStream saveFile = new FileStream("Test.txt", FileMode.Create, FileAccess.Write);
            serializer.Serialize(saveFile, tests);
            saveFile.Close();

            //反序列化
            FileStream loadFile = new FileStream("Test.txt", FileMode.Open, FileAccess.Read);
            List<Test> tests2 = serializer.Deserialize(loadFile) as List<Test>;
            foreach (Test item in tests2)
            {
                Console.WriteLine(item);
            }
            Console.ReadKey();

        }

 

C#之序列化对象(二进制方式序列化对象)

原文:http://www.cnblogs.com/lfxiao/p/6764898.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!