C#2008与.NET 3.5 高级程序设计读书笔记(21)-- 对象序列化
2010-08-11 09:52
357 查看
1.对象序列化
术语序列化(serialization)描述了持久化(可能还包括传输)一个对象状态到流(如文件流,内存流)的过程.
当试图通过.NET远程处理层,XML Web服务或WCF这样的远程处理技术将一个对象复制到远程计算机时,具有对类型序列化的能力很关键.
虽然使用.NET序列化保存对象非常简单,但幕后的调用过程却非常复杂.例如,当一个对象被持久化到流时,所有的相关数据(基类,包含的对象等)也会被自动序列化.
2.为序列化配置对象
只需为每个类加上[Serializable]特性,如果要排除某些域,只需在前面加上[NonSerialized]
如:
字段的类型对序列化的影响,如下
代码
术语序列化(serialization)描述了持久化(可能还包括传输)一个对象状态到流(如文件流,内存流)的过程.
当试图通过.NET远程处理层,XML Web服务或WCF这样的远程处理技术将一个对象复制到远程计算机时,具有对类型序列化的能力很关键.
虽然使用.NET序列化保存对象非常简单,但幕后的调用过程却非常复杂.例如,当一个对象被持久化到流时,所有的相关数据(基类,包含的对象等)也会被自动序列化.
2.为序列化配置对象
只需为每个类加上[Serializable]特性,如果要排除某些域,只需在前面加上[NonSerialized]
如:
[Serializable] public class Radio { public bool hasTweeters; public bool hasSubWoofers; public double[] stationPresets; [NonSerialized] public string radioID = "XF-552RR6"; }
字段的类型对序列化的影响,如下
代码
[Serializable]
public class Car
{
public Radio theRadio = new Radio();
public bool isHatchBack;
}
[Serializable, XmlRoot(Namespace = "http://www.intertech.com")]
public class JamesBondCar : Car
{
[XmlAttribute]
public bool canFly;
[XmlAttribute]
public bool canSubmerge;
public JamesBondCar(bool skyWorthy, bool seaWorthy)
{
canFly = skyWorthy;
canSubmerge = seaWorthy;
}
// The XmlSerializer demands a default constructor!
public JamesBondCar() { }
}
[Serializable] public class Radio { public bool hasTweeters; public bool hasSubWoofers; public double[] stationPresets; [NonSerialized] public string radioID = "XF-552RR6"; }
class Program
{
static void Main(string[] args)
{
Console.WriteLine("***** Fun with Object Serialization *****\n");
// Make a JamesBondCar and set state.
JamesBondCar jbc = new JamesBondCar();
jbc.canFly = true;
jbc.canSubmerge = false;
jbc.theRadio.stationPresets = new double[] { 89.3, 105.1, 97.1 };
jbc.theRadio.hasTweeters = true;
// Now save / Load the car to a specific file.
SaveAsBinaryFormat(jbc, "CarData.dat");
LoadFromBinaryFile("CarData.dat");
SaveAsSoapFormat(jbc, "CarData.soap");
SaveAsXmlFormat(jbc, "CarData.xml");
SaveListOfCars();
SaveListOfCarsAsBinary();
Console.ReadLine();
}
#region Save / Load as Binary Format
static void SaveAsBinaryFormat(object objGraph, string fileName)
{
// Save object to a file named CarData.dat in binary.
BinaryFormatter binFormat = new BinaryFormatter();
using (Stream fStream = new FileStream(fileName,
FileMode.Create, FileAccess.Write, FileShare.None))
{
binFormat.Serialize(fStream, objGraph);
}
Console.WriteLine("=> Saved car in binary format!");
}
static void LoadFromBinaryFile(string fileName)
{
BinaryFormatter binFormat = new BinaryFormatter();
// Read the JamesBondCar from the binary file.
using (Stream fStream = File.OpenRead(fileName))
{
JamesBondCar carFromDisk =
(JamesBondCar)binFormat.Deserialize(fStream);
Console.WriteLine("Can this car fly? : {0}", carFromDisk.canFly);
}
}
#endregion
#region Save as SOAP Format
// Be sure to import System.Runtime.Serialization.Formatters.Soap
// and reference System.Runtime.Serialization.Formatters.Soap.dll.
static void SaveAsSoapFormat(object objGraph, string fileName)
{
// Save object to a file named CarData.soap in SOAP format.
SoapFormatter soapFormat = new SoapFormatter();
using (Stream fStream = new FileStream(fileName,
FileMode.Create, FileAccess.Write, FileShare.None))
{
soapFormat.Serialize(fStream, objGraph);
}
Console.WriteLine("=> Saved car in SOAP format!");
}
#endregion
#region Save as XML Format
static void SaveAsXmlFormat(object objGraph, string fileName)
{
// Save object to a file named CarData.xml in XML format.
XmlSerializer xmlFormat = new XmlSerializer(typeof(JamesBondCar),
new Type[] { typeof(Radio), typeof(Car) });
using (Stream fStream = new FileStream(fileName,
FileMode.Create, FileAccess.Write, FileShare.None))
{
xmlFormat.Serialize(fStream, objGraph);
}
Console.WriteLine("=> Saved car in XML format!");
}
#endregion
#region Save collection of cars
static void SaveListOfCars()
{
// Now persist a List<> of JamesBondCars.
List<JamesBondCar> myCars = new List<JamesBondCar>();
myCars.Add(new JamesBondCar(true, true));
myCars.Add(new JamesBondCar(true, false));
myCars.Add(new JamesBondCar(false, true));
myCars.Add(new JamesBondCar(false, false));
using (Stream fStream = new FileStream("CarCollection.xml",
FileMode.Create, FileAccess.Write, FileShare.None))
{
XmlSerializer xmlFormat = new XmlSerializer(typeof(List<JamesBondCar>),
new Type[] { typeof(JamesBondCar), typeof(Car), typeof(Radio) });
xmlFormat.Serialize(fStream, myCars);
}
Console.WriteLine("=> Saved list of cars!");
}
static void SaveListOfCarsAsBinary()
{
// Save ArrayList object (myCars) as binary.
List<JamesBondCar> myCars = new List<JamesBondCar>();
BinaryFormatter binFormat = new BinaryFormatter();
using (Stream fStream = new FileStream("AllMyCars.dat",
FileMode.Create, FileAccess.Write, FileShare.None))
{
binFormat.Serialize(fStream, myCars);
}
Console.WriteLine("=> Saved list of cars in binary!");
}
#endregion
}
相关文章推荐
- C#2008与.NET 3.5 高级程序设计读书笔记(8)--对象的生命周期
- C# 与 .Net 3.5 高级程序设计(第四版) 读书笔记(二)
- C# 与 .Net 3.5 高级程序设计(第四版) 读书笔记(三)
- C# 与 .Net 3.5 高级程序设计(第四版) 读书笔记(一)
- C#2008与.NET 3.5 高级程序设计读书笔记(10)-- 集合与泛型
- C#2008与.NET 3.5 高级程序设计读书笔记(3)--C#核心编程结构I
- C#2008与.NET 3.5 高级程序设计读书笔记(27)-- WindowsForms编程
- C#2008与.NET 3.5 高级程序设计读书笔记(4)--C#核心编程结构II
- C#2008与.NET 3.5 高级程序设计读书笔记(12)-- 索引器
- C#2008与.NET 3.5 高级程序设计读书笔记(25)-- WCF
- C#2008与.NET 3.5 高级程序设计读书笔记(24)-- LINQ API编程
- C#2008与.NET 3.5 高级程序设计读书笔记(5)--定义封装的类类型
- C#2008与.NET 3.5 高级程序设计读书笔记(13)-- C#3.0的语言功能
- C#2008与.NET 3.5 高级程序设计读书笔记(16)-- 类型反射、晚期绑定和基于特性的编程
- C#2008与.NET 3.5 高级程序设计读书笔记(32)-- ASP.NET Web控件、主题和母版页
- C#2008与.NET 3.5 高级程序设计读书笔记(14)-- LINQ
- C#2008与.NET 3.5 高级程序设计读书笔记(31)-- 构建ASP.NET网页
- C#2008与.NET 3.5 高级程序设计读书笔记(1)--.NET之道
- C#2008与.NET 3.5 高级程序设计读书笔记(6)--继承和多态
- C#2008与.NET 3.5 高级程序设计读书笔记(15)-- .NET程序集入门