在 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("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,里边有记录对象的相关信息。内容如下所示 -