C#之序列化对象(二进制方式序列化对象)
2017-04-25 22:06
253 查看
应用程序有时需要以对象的形式在磁盘上存储数据,FrameWork有两个可用的实现方式:
一:System.Runtime.Serialization.Formatters.Binarry这个名称空间包含了BinarryFormatter类,它能把对象序列化为二进制数据,把二进制数据序列化为对象
二:System.Runtime.Serialization.Formatters.Soap:这个名称空间中包含了类SoapFormat类,它能把对象序列化为Soap格式的XML数据
以上两个类都实现了IFormatter接口,IFormatter接口提供了下面两个方法:
BinaryFormatter序列化、反序列化对象
[Serializable] class Test { public long Id; public string Name; public double Price; [NonSerialized] string Notes; public Test(long id, string name, double price, string notes) { this.Id = id; this.Name = name; this.Price = price; this.Notes = notes; } public override string ToString() { return string.Format("{0}:{1} (${2:F2}) {3}", Id, Name, Price, Notes); }
static void Main(string[] args) { List<Test> tests = new List<Test>(); tests.Add(new Test(1, "苹果", 5.5, "烟台红富士")); tests.Add(new Test(2, "菠萝", 3.5, "海南菠萝")); tests.Add(new Test(3, "樱桃", 100, "智利樱桃")); //用于序列化和反序列化的对象 IFormatter serializer = new BinaryFormatter(); //开始序列化 FileStream saveFile = new FileStream("Test.txt", FileMode.Create, FileAccess.Write); serializer.Serialize(saveFile, tests); saveFile.Close(); //反序列化 FileStream loadFile = new FileStream("Test.txt", FileMode.Open, FileAccess.Read); List<Test> tests2 = serializer.Deserialize(loadFile) as List<Test>; foreach (Test item in tests2) { Console.WriteLine(item); } Console.ReadKey(); }
相关文章推荐
- C# 对象二进制序列化
- C# 以二进制序列化DataSet对象
- C# 对象二进制序列化
- C#通过序列化的方式存读类、结构、数组等为二进制文件
- C#复杂对象序列化,推荐二进制
- C# .Net 对象二进制序列化
- C#对象的浅拷贝,深拷贝及利用序列化等多种方式实现深拷贝
- C#把对象序列化成二进制文件
- c#对象序列化(二进制序列化)BinaryFormatter【转】
- C#对象的浅拷贝,深拷贝及利用序列化等多种方式实现深拷贝
- C# 对象二进制序列化
- C#对象的 Xml序列化与反序列化
- [Serializable]在C#中的作用,.NET 中的对象序列化
- C#中对象,对象集合的简单Xml序列化与反序列化
- (转)Serializable在C#中的作用.NET 中的对象序列化
- [Serializable]在C#中的作用-NET 中的对象序列化
- [Serializable]在C#中的作用-NET 中的对象序列化
- Serializable在C#中的作用.NET 中的对象序列化
- 对象的序列化与反序列化,以xml,二进制流的方式,soap方式序列化对象
- [Serializable]在C#中的作用-NET 中的对象序列化