本文概述
在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
如你所见,序列化的数据存储在文件中。要获取数据,你需要执行反序列化。
评论前必须登录!
注册