C#序列化

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

序列化可在远程应用程序的内部使用。

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("F:\\worksp\\csharp\\serialize.txt", FileMode.OpenOrCreate);
        BinaryFormatter formatter = new BinaryFormatter();

        Student s = new Student(1010, "Curry");
        formatter.Serialize(stream, s);

        stream.Close();
    }
}

执行上面示例代码后,应该可以在F:\worksp\csharp目录看到创建了一个文件:serialize.txt,里边有记录对象的相关信息。内容如下所示 -


上一篇: C# DirectoryInfo类 下一篇: C#反序列化