There is an attribute for this purpose.
Implement the following method on any object that you want to deserialize:
[OnDeserialized]
internal void OnDeserializedMethod(StreamingContext context) {
}
There System.Runtime.Serializationare a few more attributes that can help you.
EDIT
I changed the code a bit:
[Serializable]
public class Pony {
public int Id {
get; set;
}
public string Name {
get; set;
}
public Pony BFF {
get; set;
}
public Pony() {
}
[OnDeserialized]
internal void OnDeserializedMethod(StreamingContext context) {
Console.WriteLine(this.Id + " " + this.Name + " " + this.BFF?.Name);
}
}
TestMethod:
var rd = new Pony { Id = 1, Name = "Rainbow Dash" };
var fs = new Pony { Id = 2, Name = "Fluttershy", BFF = rd };
rd.BFF = fs;
var ponies = new List<Pony> { rd, fs };
object returnValue;
using (var memoryStream = new MemoryStream()) {
var binaryFormatter = new BinaryFormatter();
binaryFormatter.Serialize(memoryStream, ponies);
memoryStream.Position = 0;
returnValue = binaryFormatter.Deserialize(memoryStream);
}
var xx = (List<Pony>)returnValue;
, ISerializable, GetObjectData - .
, , , , (De) Serialization.
EDIT 2 ( ):
One ( )
...
private Pony(SerializationInfo info, StreamingContext context) {
foreach (SerializationEntry entry in info) {
switch (entry.Name) {
case "Id":
this.Id = (int)entry.Value;
break;
case "Name":
this.Name = (string)entry.Value;
break;
case "BFF":
this.BFF = (Pony)entry.Value;
break;
}
}
}
public void GetObjectData(SerializationInfo info, StreamingContext ontext) {
info.AddValue("Id", Id);
info.AddValue("Name", Name);
info.AddValue("BFF", BFF);
}
}
...
2 ( - Id):
...
private Pony(SerializationInfo info, StreamingContext context) {
foreach (SerializationEntry entry in info) {
switch (entry.Name) {
case "Id":
this.Id = (int)entry.Value;
break;
case "Name":
this.Name = (string)entry.Value;
break;
case "BFF.Id":
var bffId = (int)entry.Value;
this.BFF = GetPonyById(bffId);
break;
}
}
}
public void GetObjectData(SerializationInfo info, StreamingContext ontext) {
info.AddValue("Id", Id);
info.AddValue("Name", Name);
info.AddValue("BFF.Id", BFF.Id);
}
...