C#序列化与反序列化

我们可以通过给类添加Serializable特性,使其可以序列化与反序列化.通俗的说,就是能将这个类的对象信息保存到本地,也可以通过保存到本地的对象信息实例化对象.

首先,写一个Utils工具类来实现序列化与反序列化:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

namespace ConsoleApplication1
{
    class Utils
    {
        private BinaryFormatter bf;

        public Utils ()
        {
            bf = new BinaryFormatter();
        }

        public void Serialize<T> (string path, T obj) where T: class
        {
            FileStream fs = new FileStream(path,  FileMode.OpenOrCreate);
            bf.Serialize(fs, obj);
            fs.Close();
        }

        public T Deserialize<T>(string path) where T : class
        {
            if (!File.Exists (path))
            {
                Console.WriteLine("文件不存在: {0}", path);
                return null;
            }

            FileStream fs = new FileStream(path, FileMode.Open);
            T obj = bf.Deserialize(fs) as T;
            fs.Close();
            return obj;
        }
    }
}

写一个测试类Person:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    [Serializable]
    class Person
    {
        private string flag;
        public string Flag
        {
            get
            {
                return flag;
            }
            set
            {
                flag = value;
            }
        }

        public string name;
    }
}

测试:

#define debug

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string path = @"E:\Person.txt";

            Person p = new Person();
            p.name = "王二狗";
            p.Flag = "大家好,我是flag";

            Utils utils = new Utils();
            utils.Serialize<Person>(path, p);

            Person p2 = utils.Deserialize<Person>(path);
            Console.WriteLine("p2.name: {0}, p2.Flag: {1}", p2.name, p2.Flag);
        }
    }
}

项目中用来存储进度信息蛮好用的.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值