To use the default serialization, you must mark a class with the [Serializable] attribute. You can use the [NonSerialized] attribute to prevent an object from being serialized.
Under the hood, we use the ObjectIDGenerator class to generate unique ID for objects that we serialize and ObjectManager to track objects as they are being deserialized.
The following example demonstrates custom serialization.
using System;
using System.IO;
using System.Collections;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security.Permissions;
namespace Test.Ch17
{
public class MyMain
{
public static int Main()
{
MyMain M = new MyMain();
M.ToFile();
M.FromFile();
return 0;
}
public void ToFile()
{
Console.WriteLine("ToFile");
Foo F = new Foo();
F.a = 5;
F.b = 10;
F.c = "HelloWorld!";
Foo F1 = new Foo();
F1.a = 20;
F1.b = 30;
F1.c = "Greg";
Console.WriteLine("The value of Foo.a is: {0}", F.a);
Console.WriteLine("The value of Foo.b is: {0}", F.b);
Console.WriteLine("The value of Foo.c is: {0}", F.c);
IFormatter MyFormatter = new BinaryFormatter();
Stream MyStream = new FileStream("Foo.xml",
FileMode.Create, FileAccess.Write, FileShare.None);
MyFormatter.Serialize(MyStream, F);
MyFormatter.Serialize(MyStream, F1);
MyStream.Close();
}
public void FromFile()
{
Console.WriteLine("FromFile");
IFormatter MyFormatter = new BinaryFormatter();
Stream MyStream = new FileStream("Foo.xml",
FileMode.Open, FileAccess.Read,
FileShare.Read);
Foo F1 = (Foo)MyFormatter.Deserialize(MyStream);
Foo F = (Foo)MyFormatter.Deserialize(MyStream);
MyStream.Close();
Console.WriteLine("The value of Foo1.a is: {0}", F1.a);
Console.WriteLine("The value of Foo1.b is: {0}", F1.b);
Console.WriteLine("The value of Foo1.c is: {0}", F1.c);
Console.WriteLine("The value of Foo.a is: {0}", F.a);
Console.WriteLine("The value of Foo.b is: {0}", F.b);
Console.WriteLine("The value of Foo.c is: {0}", F.c);
}
}
[Serializable]
public class Foo : ISerializable
{
public int a,b;
public string c = "HelloWorld!";
public Foo(){}
//Allows for custom deserialization
public Foo(SerializationInfo si, StreamingContext context)
{
c = si.GetString("c");
a = si.GetInt32("a");
b = si.GetInt32("b");
}
//Allows for custom serialization
public void GetObjectData(SerializationInfo si,
StreamingContext context)
{
si.AddValue("a", a);
si.AddValue("b", b);
si.AddValue("c", c);
//Type T = Foo.GetType();
//si.AddValue("Type", T);
}
}
}