序列化与反序列化
Posted time-fly
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了序列化与反序列化相关的知识,希望对你有一定的参考价值。
using System;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
//using System.Runtime.Serialization.Formatters.Binary;
namespace 序列化与反序列化 {
class Program {
public static void Main(String[] args) {
//序列化
//Person p = new Person();
//p.Name = "张三";
//p.Age = 20;
//p.Gender = ‘f‘;
//using (FileStream fswrite = new FileStream(@"f:Person.txt", FileMode.CreateNew, FileAccess.Write)) {
// BinaryFormatter bf = new BinaryFormatter();
// bf.Serialize(fswrite,p);
//}
//反序列化
Person p;
using (FileStream fsread = new FileStream(@"f:Person.txt", FileMode.Open, FileAccess.Read)) {
BinaryFormatter bf = new BinaryFormatter();
p = bf.Deserialize(fsread) as Person;
}
Console.WriteLine(p.Name);
Console.WriteLine(p.Age);
Console.WriteLine(p.Gender);
}
}
[Serializable]
class Person {
private string _name;
private int _age;
private char _gender;
public string Name { get => _name; set => _name = value; }
public int Age { get => _age; set => _age = value; }
public char Gender { get => _gender; set => _gender = value; }
}
}
以上是关于序列化与反序列化的主要内容,如果未能解决你的问题,请参考以下文章