C# 序列化
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("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
如您所见,序列化数据存储在文件中。获取数据需要进行反序列化。