继承BinaryFormatter()类
[Serializable]//允许这个对象序列化 public class Person { public int Id { get; set; } public string Name { get; set; } public int Age { get; set; } }
序列化
BinaryFormatter binaryFormatter = new BinaryFormatter(); if (!File.Exists("person.bin"))//判断是否读取到这个文件 { Person person = new Person()//给对象赋值 { Id = 1, Name = "Test", Age = 23 }; //将对象序列化为二进制数据 using (FileStream stream = new FileStream("person.bin", FileMode.Create)) { binaryFormatter.Serialize(stream, person); } }
反序列化
//从文件反序列化 using (FileStream stream1 = new FileStream("person.bin", FileMode.Open)) { Person person1 = (Person)binaryFormatter.Deserialize(stream1); //var person1 = binaryFormatter.Deserialize(stream1); Console.WriteLine("111"); Console.WriteLine(person1); ListViewItem item = new ListViewItem(); item.SubItems[0].Text = person1.Id.ToString(); item.SubItems.Add(person1.Name); item.SubItems.Add(person1.Age.ToString()); listView1.Items.Add(item); }
标签:person,Person,item,person1,new,序列化 From: https://www.cnblogs.com/lin-07/p/17633946.html