在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
如您所见,序列化数据存储在文件中。要获取数据,您需要执行反序列化。
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)