序列化就是将类对象的数据存储到文件的过程,反序列化就是将文件内容重新加载到内存,重新形成对象的过程,其中我们会使用 XmlSerializer类进行序列化的操作,这个操作有几大特点:
//1.序列化的类必须是public访问修饰符。
//2.类里必须要有无参构造函数。
//3.不需要序列化的属性要使用private。
//4.不需要序列化的字段的值和反序列时显示字段的值,那么初始化就在构造函数中完成,且不要给默认值。
//创建一个类
public class Play //必须是public访问修饰符
{
private string name;
private int age;
private int id;
private string nation;
public Play() //必须有无参构造函数
{
}
public Play(string name, int age, int id,string nation)
{
this.Name = name;
this.Age = age;
this.Id = id;
this.Nation = nation;
}
public string Name { get => name; set => name = value; }
public int Age { get => age; set => age = value; }
public int Id { get => id; set => id = value; }
private string Nation { get => nation; set => nation = value; } //不想序列化的属性使用private
//重写
public override string ToString()
{
return $"name={this.name},age={this.age},id={this.id},nation={this.nation}";
}
}
public class demo1
{
internal static void Main(string[] strings)
{
Play play = new Play("jack", 18, 43285, "china");
//序列化操作。using 可以自动释放资源,因为play对象是二进制文件,用filestream来处理。using语句是一种方便的语法结构,用于确保在使用完一个实现了IDisposable接口的对象后,自动释放该对象所占用的资源。
using (FileStream fs=new FileStream("C:\\Users\\11442\\Desktop\\1",FileMode.OpenOrCreate,FileAccess.Write))
{
//fs.write()的参数是字节数组,play类对象无法转换,所以这里通过XmlSerializer类来处理。
XmlSerializer xs = new XmlSerializer(typeof(ldd.Play));
<