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

本文介绍如何使用.NET Framework中的BinaryFormatter类进行对象的序列化与反序列化操作,并提供了一个具体的示例代码,展示了如何将对象序列化为二进制数据并将其存储到文件中,以及如何从该文件中读取数据并反序列化为对象。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

应用程序有时需要以对象的形式在磁盘上存储数据,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();

        }

 

转载于:https://www.cnblogs.com/lfxiao/p/6764898.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值