When we don’t want some of the fields of a class to serialize with the object, we may like to perform some work on the object when de-serializing so that we may prepare the non-serialized fields. This is useful when the state of some of fields is dependant on the other fields and it does not make sense to serialize them for performance issues. For this, we need to implement the IDeserialization Interface. This interface has only one method OnDeserialization, which is called when the object is de-serialized. It is in this method we may put the logic of computation of the other fields from the serialized fields.
This is an Employee class which has a field call netSalary, which is 70% of the grossSalary field. We have marked the field netSalary as [NonSerialized] so that it is not serialized. But it is calculated back from the grossSalary field upon de-serialization.
[Serializable] public class Employee : IDeserializationCallback { string name; int id; double grossSalary; [NonSerialized] double netSalary;
public Employee(string name, int id, double grossSalary) { this.name = name; this.id = id; this.grossSalary = grossSalary; }
public Employee() { }
public override string ToString() { return "name:" + name + ", id:" + id + ", grossSalary:" + grossSalary + ", netSalary:" + netSalary; }
#region IDeserializationCallback Members
public void OnDeserialization(object sender) { netSalary = 0.7 * grossSalary; }
#endregion
public void Serialize(string fileName) { FileInfo fileInfo = new FileInfo(fileName); FileStream fileStream = fileInfo.Open(FileMode.Create, FileAccess.Write, FileShare.None); BinaryFormatter form = new BinaryFormatter(); form.Serialize(fileStream, this); fileStream.Close(); }
public void Deserialize(string fileName) { FileInfo fileInfo = new FileInfo(fileName); FileStream fileStream = fileInfo.Open(FileMode.Open, FileAccess.Read, FileShare.None); BinaryFormatter form = new BinaryFormatter(); Employee employee = (Employee)form.Deserialize(fileStream); fileStream.Close(); this.name = employee.name; this.id = employee.id; this.grossSalary = employee.grossSalary; this.netSalary = employee.netSalary; } }
Here is some quick test code:
new Employee("pdas", 1240, 50000.00).Serialize(@"D:\chasrp.txt"); //forget about the above object; create a new one from the serailized data: Employee copyOfEmployee = new Employee(); copyOfEmployee.Deserialize(@"D:\chasrp.txt"); Console.WriteLine(copyOfEmployee); Console.ReadLine();
|
No responses found. Be the first to respond and make money from revenue sharing program.
|