在 C# 编程中,反序列化是序列化的相反过程。开发人员可以从字节流中读取内容并转为对象。在这里,我们将使用BinaryFormatter.Deserialize(stream)
方法反序列化流。
C# 反序列化示例
下面来看看 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