C#中类的序列化和反序列化
说明:本文演示将类序列化后写入记事本并从记事本读取反序列化为对象
1.首先创建一个类,同时类必须标识为Serializable,如下:
[Serializable] public class Region { public String _id { get; set; } public String region_id { get; set; } public String region_name { get; set; } public String parent_region_id { get; set; } }
2.序列化代码如下
//定义对象 Region region = new Region() { region_name = "ABCD" }; byte[] bytes; //序列化并写入内存流 using (MemoryStream ms = new MemoryStream()) { IFormatter formatter = new BinaryFormatter(); //序列化 formatter.Serialize(ms, region); bytes=ms.GetBuffer(); } //将内存流写入文件 FileStream fs = new FileStream("aa.txt", FileMode.OpenOrCreate); fs.Write(bytes, 0, bytes.Length); fs.Close();
3.反序列化代码如下
//将文件读取为文件流并写入byte数组 FileStream fs = new FileStream("aa.txt", FileMode.OpenOrCreate); var length=Convert.ToInt32(fs.Length); byte[] bytes = new byte[length]; fs.Read(bytes, 0, length); //将byte数组写入内存流 using (MemoryStream ms = new MemoryStream(bytes)) { IFormatter formatter = new BinaryFormatter(); //反序列化后强制转换 Region region = (Region)formatter.Deserialize(ms); Console.WriteLine(region.region_name); }
说明:经本人测试没有任何问题