Existen varias opciones dependiendo del tipo de serializador.
Si usted podría utilizar DataContractSerializer o BinaryFormatter entonces puede usar OnSerializedAttribute y establezca la propiedad Parent para su objeto secundario a esto:
[Serializable]
public class Child
{
public string Foo { get; set; }
public Parent Parent { get { return parent; } set { parent = value; } }
// We don't want to serialize this property explicitly.
// But we could set it during parent deserialization
[NonSerialized]
private Parent parent;
}
[Serializable]
public class Parent
{
// BinaryFormatter or DataContractSerializer whould call this method
// during deserialization
[OnDeserialized()]
internal void OnSerializedMethod(StreamingContext context)
{
// Setting this as parent property for Child object
Child.Parent = this;
}
public string Boo { get; set; }
public Child Child { get; set; }
}
class Program
{
static void Main(string[] args)
{
Child c = new Child { Foo = "Foo" };
Parent p = new Parent { Boo = "Boo", Child = c };
using (var stream1 = new MemoryStream())
{
DataContractSerializer serializer = new DataContractSerializer(typeof (Parent));
serializer.WriteObject(stream1, p);
stream1.Position = 0;
var p2 = (Parent)serializer.ReadObject(stream1);
Console.WriteLine(object.ReferenceEquals(p, p2)); //return false
Console.WriteLine(p2.Boo); //Prints "Boo"
//Prints: Is Parent not null: True
Console.WriteLine("Is Parent not null: {0}", p2.Child.Parent != null);
}
}
}
Si desea utilizar XmlSerializer debe implementar IXmlSerializable, utilice XmlIgnoreAttribute y una aplicación más o menos la misma lógica en el método ReadXml. Pero en este caso también debería implementar manualmente toda la lógica de serialización Xml:
[Serializable]
public class Child
{
public Child()
{
}
public string Foo { get; set; }
[XmlIgnore]
public Parent Parent { get; set; }
}
[Serializable]
public class Parent
{
public Parent()
{
}
#region IXmlSerializable Members
public System.Xml.Schema.XmlSchema GetSchema()
{
throw new NotImplementedException();
}
public void ReadXml(System.Xml.XmlReader reader)
{
//Reading Parent content
//Reading Child
Child.Parent = this;
}
public void WriteXml(System.Xml.XmlWriter writer)
{
//Writing Parent and Child content
}
#endregion
public string Boo { get; set; }
public Child Child { get; set; }
}
Si hago eso, entonces la referencia desaparece cuando deserializo el objeto. Objeto proviene de un servicio de WCF – Rachel
¡Gracias! Tu edición aclaró cosas ... Me olvidé por completo de que podía agregar el padre '[OnDeserializing()]', que es lo que terminé haciendo. – Rachel
Como mencioné con el comentario de las respuestas de AHM, OnDeserializingAttribute es redundante en este caso, porque aún funciona bien sin él. Pero aún podría agregar algo de lógica adicional en este método. –