部份代码:
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Text;
using
using System.Runtime.Serialization.Formatters.Binary;
namespace Persistency
{
[Serializable]
public class MyObject
{
public int n1 = 0;
public int n2 = 0;
public String str = null;
public MySecondObject ms=new MySecondObject();
}
[Serializable]
public class MySecondObject
{
public int n1 = 0;
public int n2 = 0;
public String str = "This is an object of class MySecondObject";
}
class Program
{
static void Main(string[] args)
{
Serialize();
Deserialize();
Console.ReadLine();
}
static void Serialize()
{
MyObject obj = new MyObject();
obj.n1 = 1;
obj.n2 = 24;
obj.str = "Some String";
IFormatter formatter = new BinaryFormatter();
Stream stream = new FileStream("MyFile.bin", FileMode.Create, FileAccess.Write, FileShare.None);
formatter.Serialize(stream, obj);
stream.Close();
Console.ReadLine();
}
static void Deserialize()
{
// Declare the hashtable reference.
MyObject obj = null;
// Open the file containing the data that you want to deserialize.
FileStream fs = new FileStream("MyFile.bin", FileMode.Open);
try
{
BinaryFormatter formatter = new BinaryFormatter();
// Deserialize the hashtable from the file and
// assign the reference to the local variable.
obj = (MyObject)formatter.Deserialize(fs);
}
catch (SerializationException e)
{
Console.WriteLine("Failed to deserialize. Reason: " + e.Message);
throw;
}
finally
{
fs.Close();
Console.WriteLine(obj.ms.str);
}
}
}
}