Serialization technology(序列化技术)
一、为什么要用序列化技术
主要作用:
1.Persistence(持久化对象):序列化到一个文件系统中
Store and retrieve a graph of objects to and from a file
2..Net Remoting
Pass by value arguments that are transmitted between processes
二、Serialization Attributes
1.To Mark a Class, Use Serializable Attribute
[Serializable] public class MyClass {}
2.To Skip Specified Members, Use NonSerialized Attribute
[Serializable] public class MyClass { [NonSerialized] int _cashSize; //... }
3.To Provide Custom Serialization, Implement ISerializable
三、Object Graph
Serialization Manage Automatically
四、Serialization Process(序列化过程)
Classes Used by the Default Serialization Process
ObjectIDGenerator – generates IDs for objects
ObjectManager – tracks objects as they are being deserialized
Examples of Classes Used with Serialized Streams
FileStream, MemoryStream, NetworkStream
Formatter Class
Writes or reads data in a specified format to the output or input streams
Runtime provides BinaryFormatter , SoapFormatter and XmlSerializer
五、Serialize Class and object
Example:
class SerializeExample
{
public static void Main(String[] args)
{ // create the object graph
ArrayList l = new ArrayList();
for (int x=0; x< 100; x++)
{
l.Add (x);
}
// create the filestream
FileStream s = File.Create("foo.bin");
// create the BinaryFormatter
BinaryFormatter b = new BinaryFormatter();
// serialize the graph to the stream
b.Serialize(s, l);
s.Close();
}
}
六、Deserialize Class and object
Example:
class DeSerialize
{
public static void Main(String[] args)
{ // open the filestream
FileStream s = File.OpenRead("foo.bin");
// create the formatter
BinaryFormatter b = new BinaryFormatter();
// deserialize
ArrayList p = (ArrayList) b.Deserialize(s); s.Close();
// print out the new object graph
// see module text for PrintValues’ code
PrintValues(p);
}
}
七、Security Issues
Serialization Handles an Object’s Private Data
If private data is sensitive, consider encrypting the stream before transmitting or saving to a disk
System.Security.Cryptography namespace contains classes to perform cryptography The CryptoStream class can be used to encrypt streams of serialized data