在 c# 编程中,反序列化是序列化的相反过程。开发人员可以从字节流中读取内容并转为对象。在这里,我们将使用binaryformatter.deserialize(stream)
方法反序列化流。
下面来看看 c# 中的反序列化的简单例子。参考以下示例代码 -
using system;
using system.io;
using system.runtime.serialization.formatters.binary;
[serializable]
class student
{
public int rollno;
public string name;
public student(int rollno, string name)
{
this.rollno = rollno;
this.name = name;
}
}
public class deserializeexample
{
public static void main(string[] args)
{
filestream stream = new filestream(@"f:\worksp\csharp\serialize.txt", filemode.openorcreate);
binaryformatter formatter = new binaryformatter();
student s = (student)formatter.deserialize(stream);
console.writeline("rollno: " + s.rollno);
console.writeline("name: " + s.name);
stream.close();
}
}
执行上面示例代码,得到以下结果 -
rollno: 1010
name: curry