在 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("e:\\sss.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: 101 Name: sonoo