Serialize对象二进制序列化与反序列化存储参数代替ini文件

序列化是将对象的状态信息转换为可以存储或传输的形式的过程。在C#中,可以使用System.Runtime.Serialization命名空间中的类来进行序列化操作。

以下是在C#中使用序列化的基本步骤:

  1. 创建一个可序列化的类,并标记该类和需要序列化的属性或字段,使用[Serializable]特性进行标记。

    [Serializable]  
    public class Person  
    {  
        public int ID { get; set; }  
        public string Name { get; set; }  
    }

  2. 创建一个BinaryFormatter对象,并使用它将对象序列化为二进制格式。

BinaryFormatter formatter = new BinaryFormatter();  
using (FileStream stream = new FileStream("person.bin", FileMode.Create))  
{  
    formatter.Serialize(stream, person);  
}

上述代码将person对象序列化为二进制格式,并保存到名为"person.bin"的文件中。您可以根据需要更改文件名和路径。

        3.反序列化对象,使用BinaryFormatter将二进制数据转换回为对象。

BinaryFormatter formatter = new BinaryFormatter();  
using (FileStream stream = new FileStream("person.bin", FileMode.Open))  
{  
    Person deserializedPerson = (Person)formatter.Deserialize(stream);  
}

上述代码将从名为"person.bin"的文件中反序列化Person对象。

请注意,序列化和反序列化是在内存中进行的操作,因此如果您的对象很大或很复杂,可能会导致性能问题。此外,反序列化过程可能会引发异常,例如如果文件损坏或格式不正确。因此,在使用序列化时,应该注意错误处理和异常情况。

实际使用例程

 

存储配置,相应的代码实例

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {

        public Form1()
        {
            InitializeComponent();
        }
        //参考代码讲解 https://www.bilibili.com/video/BV16V411V7D3/?spm_id_from=333.999.0.0&vd_source=e821a225c7ba4a7b85e5aa6d013ac92e

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                //实例化对象
                person p = new person();
                p.name = textBox1.Text;
                p.age = Convert.ToInt32(textBox2.Text);
                p.pic = pictureBox1.Image;
                
                p.tags.Add(textBox1.Text);
                p.tags.Add(textBox2.Text);
                p.tags.Add("kkk");

                //序列化对象
                string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, p.name + ".db");

                using(FileStream fs = new FileStream(filePath,FileMode.Create,FileAccess.Write)) {
                    BinaryFormatter binFormat = new BinaryFormatter(); //创建二进制序列化器
                    binFormat.Serialize(fs, p);  //将对象序列化到流中
                }
                MessageBox.Show("序列化成功!", "提示");
            }catch (Exception ex)
            {
                MessageBox.Show("序列化保存出错" + ex.ToString());
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.InitialDirectory = AppDomain.CurrentDomain.BaseDirectory; //设置初始目录
            openFileDialog.Multiselect = false;
            openFileDialog.Filter = "PNG图像(*.png)|*.png|JPG图像(*.jpg)|*.jpg"; //文件过滤
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                pictureBox1.Load(openFileDialog.FileName);  
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.InitialDirectory= AppDomain.CurrentDomain.BaseDirectory; 
            openFileDialog.Multiselect = false;
            openFileDialog.Filter = "Person对象(*.db)|*.db";//文件筛选器

            if( openFileDialog.ShowDialog() == DialogResult.OK)
            {
                string filePath = openFileDialog.FileName;
                using(FileStream fs = new FileStream(filePath,FileMode.Open,FileAccess.Read))
                {
                    try
                    {
                        BinaryFormatter binFormat = new BinaryFormatter();//创建二进制序列化器
                        person p = (person)binFormat.Deserialize(fs);
                        textBox1.Text = p.name;
                        textBox2.Text = p.age.ToString();
                        pictureBox1.Image = p.pic;

                        this.Text = p.tags.Count.ToString() + " ";

                        for( int i = 0; i < p.tags.Count; i++ )
                        {
                            this.Text += p.tags[i].ToString()+"  "; 
                        }
                        
                        

                    }catch( Exception ex )
                    {
                        MessageBox.Show("反序列化失败"+ex.Message,"提示");
                       
                    }
                }
            }

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

namespace WindowsFormsApp1
{
    [Serializable] //必须有此关键词才能序列化存储、加载
    public class person
    {
        public string name { get; set; }    
        public int age { get; set; }
        public Image pic { get; set; }

        public List<string> tags { get; set; } = new List<string>();
    }
}

特此记录

anlog

2023年8月22日

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
C#中的二进制序列是将对象转换为二进制数据的过程,以便在存储或传输时能够保留对象的状态。深入理解二进制序列可以帮助我们更好地掌握其工作原理和灵活运用。 在C#中,可以使用`BinaryFormatter`类来进行二进制序列。首先,需要将要序列对象标记为可序列,可以通过在类定义前加上`[Serializable]`特性来实现。然后,可以使用`BinaryFormatter`的`Serialize`方法将对象序列二进制数据。 以下是一个简单的示例: ```csharp [Serializable] class MyClass { public int MyProperty { get; set; } public string MyField; } class Program { static void Main() { MyClass obj = new MyClass(); obj.MyProperty = 42; obj.MyField = "Hello, world!"; BinaryFormatter formatter = new BinaryFormatter(); using (FileStream stream = File.Create("data.bin")) { formatter.Serialize(stream, obj); } } } ``` 上述代码将一个`MyClass`对象序列为名为"data.bin"的二进制文件。 要理解二进制序列的工作原理,可以了解以下几点: 1. 序列过程会将对象的字段和属性转换为字节流,并将其写入流中。序列时则会将字节流读取并转换回对象的字段和属性。 2. `BinaryFormatter`会自动处理对象图中的引用关系,确保在序列序列过程中能够正确还原对象之间的引用关系。 3. 对于自定义类型,需要确保所有要序列的字段和属性都是可序列的。非可序列的字段和属性可以通过标记为`[NonSerialized]`特性来排除。 4. 序列过程中可能会遇到无法序列的类型或对象,可以通过实现`ISerializable`接口来自定义序列序列过程。 5. 序列是一种用于持久对象状态或进行远程通信的常见技术,但需要注意安全性和性能等方面的考虑。 希望这些信息能够帮助你更深入地理解C#二进制序列的概念和使用方法。如果有任何进一步的问题,请随时提问!

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值