在 C# 中,序列化是将对象转换为字节流的过程,以便将其保存到内存、文件或数据库中。序列化的逆过程称为反序列化。
序列化在远程应用程序内部使用。
要序列化对象,您需要将SerializableAttribute属性应用于类型。如果不对类型应用SerializableAttribute属性,则会在运行时引发SerializationException异常。
让我们看一下 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
如您所见,序列化的数据存储在文件中。要获取数据,您需要执行反序列化。