using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
namespace ConsoleApp4
{
class Program
{
static void Main(string[] args)
{
List<Person> listPers = new List<Person>();
Person per1 = new Person("张三", 18);
Person per2 = new Person("李四", 20);
listPers.Add(per1);
listPers.Add(per2);
SerializeMethod(per1 );
ReserializeMethod();
Console.ReadKey();
}
static void ReserializeMethod()
{
using (FileStream fs = new FileStream("1.bin", FileMode.Open))
{
BinaryFormatter bf = new BinaryFormatter();
Person list = bf.Deserialize(fs) as Person;
}
}
static void SerializeMethod(Person listpers)
{
using (FileStream fs = new FileStream("1.bin", FileMode.OpenOrCreate))
{
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fs, listpers);
}
}
}
[Serializable]
class Person
{
public Person() { }
public Person(string name, int age)
{
this.Name = name; this.Age = age;
}
private string name;
public string Name { get => name; set => name = value; }
[NonSerialized]
private int age;//不序列化该对象
public int Age { get => age; set => age = value; }
public void SayHi() { Console.WriteLine("大家好,我是{0},今年{1}岁", name, age); }
}
}
标签:name,age,System,用法,Person,using,new,序列化
From: https://www.cnblogs.com/yuanqi99977/p/16617454.html