22 Ocak 2018 Pazartesi

ISerializable Arayüzü

Giriş
[Serializable] Anotasyonu ile beraber kullanılır. Sınıfın hangi alanlarını yazmak istediğimiz kontrol etmeye yarar. Açıklaması şöyle.
Any class that might be serialized must be marked with the SerializableAttribute. If a class needs to control its serialization process, it can implement the ISerializable interface. The Formatter calls the GetObjectData at serialization time and populates the supplied SerializationInfo with all the data required to represent the object. The Formatter creates a SerializationInfo with the type of the object in the graph. Objects that need to send proxies for themselves can use the FullTypeName and AssemblyName methods on SerializationInfo to change the transmitted information.
In the case of class inheritance, it is possible to serialize a class that derives from a base class that implements ISerializable. In this case, the derived class should call the base class implementation of GetObjectData inside its implementation of GetObjectData. Otherwise, the data from the base class will not be serialized.
Örnek
Şöyle yaparız.
[Serializable]
public class Book : ISerializable
{
  private readonly string _Title;

  protected Book(SerializationInfo info, StreamingContext context)
  {
    if (info == null)
      throw new ArgumentNullException("info");

    _Title = info.GetString("Title");
  }

  public string Title
  {
     get { return _Title; }
  }

  protected virtual void GetObjectData(SerializationInfo info, StreamingContext context)
  {
    info.AddValue("Title", _Title);
  }

}

Hiç yorum yok:

Yorum Gönder