Csharp/C Sharp by API/System.Runtime.Serialization/IDeserializationCallback — различия между версиями

Материал из .Net Framework эксперт
Перейти к: навигация, поиск
м (1 версия)
 
(нет различий)

Текущая версия на 12:11, 26 мая 2010

implements IDeserializationCallback

  
using System;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

[Serializable]
public class BookRecord : IDeserializationCallback {
    public String title;
    public int asin;
    [NonSerialized]
    public int rank;
    public BookRecord(String title, int asin) {
        this.title = title;
        this.asin = asin;
        rank = GetSalesRank();
    }
    public int GetSalesRank() {
        Random r = new Random();
        return r.Next(5000);
    }
    public void OnDeserialization(Object o) {
        rank = GetSalesRank();
    }
}

public class StreamObject {
    public static void Main() {
        BookRecord book = new BookRecord("title", 123456789);
        Console.WriteLine(book.title + " " + book.asin +" " + book.rank);
        FileStream stream = new FileStream(@"book.obj", FileMode.Create);
        BinaryFormatter bf = new BinaryFormatter();
        bf.Serialize(stream, book);
        stream.Close();
        FileStream streamIn = new FileStream(@"book.obj", FileMode.Open);
        BookRecord bookIn = (BookRecord)bf.Deserialize(streamIn);
        Console.WriteLine(bookIn.title + " " + bookIn.asin + " " + bookIn.rank);
    }
}