C#教程
C#控制语句
C#函数
C#数组
C#面向对象
C#命名空间和异常
C#文件IO
C#集合
C#多线程
C#其它

C# 序列化

C# 序列化

在 C# 中,序列化是将对象转换为字节流以便将其保存到内存、文件或数据库中的过程。序列化的逆过程称为反序列化。
序列化在远程应用程序内部使用。
C# serialization

C# SerializableAttribute

要序列化对象,您需要将 SerializableAttribute 属性应用于类型。如果您不将 SerializableAttribute 属性应用于类型,则在运行时会抛出 SerializationException 异常。

C# 序列化示例

让我们看看 C# 中序列化的简单示例,其中我们正在序列化 Student 类的对象。在这里,我们将使用 BinaryFormatter.Serialize(stream, reference) 方法来序列化对象。
using System;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
[Serializable]
class Student
{
    int rollno;
    string name;
    public Student(int rollno, string name)
    {
        this.rollno = rollno;
        this.name = name;
    }
}
public class SerializeExample
{
    public static void Main(string[] args)
    {
        FileStream stream = new FileStream("e:\\sss.txt", FileMode.OpenOrCreate);
        BinaryFormatter formatter=new BinaryFormatter();
        
        Student s = new Student(101, "sonoo");
        formatter.Serialize(stream, s);
        stream.Close();
    }
}
sss.txt:
   JConsoleApplication1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null Student rollnoname e sonoo
如您所见,序列化数据存储在文件中。获取数据需要进行反序列化。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4