C#序列化和反序列化
程序员文章站
2022-06-16 08:25:06
...
序列化
序列化导入命名空间
using System.Runtime.Serialization.Formatters.Binary;
序列化练习
class Program
{
static void Main(string[] args)
{
Person p = new Person();
p.Name = "张三";
p.Age = 18;
p.Gender = '男';
string path = @"C:\Users\lari\Desktop\新建文本文档.txt";
using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Write, FileShare.Write))
{
BinaryFormatter bf = new BinaryFormatter();
bf.Serialize(fs, p);
}
Console.WriteLine("wanshi");
Console.ReadKey();
}
[Serializable ]//标记可序列化
public class Person
{
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
private int _age;
public int Age
{
get { return _age; }
set { _age = value; }
}
private char _gender;
public char Gender
{
get { return _gender; }
set { _gender = value; }
}
public virtual void Show()//虚方法
{
Console.WriteLine("我是人");
}
}
反序列化来练习
Person p;
string path = @"C:\Users\lari\Desktop\新建文本文档.txt";
using (FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read , FileShare.Read ))
{
BinaryFormatter bf = new BinaryFormatter();
p =(Person )bf.Deserialize(fs);
}
Console.WriteLine(p.Age );
Console.WriteLine("wanshi");
Console.ReadKey();