ObjectManager Clase

Definición

Precaución

Formatter-based serialization is obsolete and should not be used.

Realiza el seguimiento de los objetos a medida que se deserializan.

public ref class ObjectManager
public class ObjectManager
[System.Obsolete("Formatter-based serialization is obsolete and should not be used.", DiagnosticId="SYSLIB0050", UrlFormat="https://aka.ms/dotnet-warnings/{0}")]
public class ObjectManager
[System.Runtime.InteropServices.ComVisible(true)]
public class ObjectManager
type ObjectManager = class
[<System.Obsolete("Formatter-based serialization is obsolete and should not be used.", DiagnosticId="SYSLIB0050", UrlFormat="https://aka.ms/dotnet-warnings/{0}")>]
type ObjectManager = class
[<System.Runtime.InteropServices.ComVisible(true)>]
type ObjectManager = class
Public Class ObjectManager
Herencia
ObjectManager
Atributos

Ejemplos

En el ejemplo de código siguiente se muestra cómo usar la ObjectManager clase para recorrer un gráfico de objetos y recorrer cada objeto una sola vez.

using System;
using System.Text;
using System.Collections;
using System.Runtime.Serialization;
using System.Reflection;

// This class walks through all the objects once in an object graph.
public sealed class ObjectWalker : IEnumerable, IEnumerator {
   private Object m_current;

   // This stack contains the set of objects that will be enumerated.
   private Stack m_toWalk = new Stack();

   // The ObjectIDGenerator ensures that each object is enumerated just once.
   private ObjectIDGenerator m_idGen = new ObjectIDGenerator();

   // Construct an ObjectWalker passing the root of the object graph.
   public ObjectWalker(Object root) {
      Schedule(root);
   }

   // Return an enumerator so this class can be used with foreach.
   public IEnumerator GetEnumerator() {
      return this;
   }

   // Resetting the enumerator is not supported.
   public void Reset() {
      throw new NotSupportedException("Resetting the enumerator is not supported.");
   }

   // Return the enumeration's current object.
   public Object Current { get { return m_current; } }

   // Walk the reference of the passed-in object.
   private void Schedule(Object toSchedule) {
      if (toSchedule == null) return;

      // Ask the ObjectIDManager if this object has been examined before.
      Boolean firstOccurrence;
      m_idGen.GetId(toSchedule, out firstOccurrence);

      // If this object has been examined before, do not look at it again just return.
      if (!firstOccurrence) return;

      if (toSchedule.GetType().IsArray) {
         // The object is an array, schedule each element of the array to be looked at.
         foreach (Object item in ((Array)toSchedule)) Schedule(item);
      } else {
         // The object is not an array, schedule this object to be looked at.
         m_toWalk.Push(toSchedule);
      }
   }

   // Advance to the next item in the enumeration.
   public Boolean MoveNext() {
      // If there are no more items to enumerate, return false.
      if (m_toWalk.Count == 0) return false;

      // Check if the object is a terminal object (has no fields that refer to other objects).
      if (!IsTerminalObject(m_current = m_toWalk.Pop())) {
         // The object does have field, schedule the object's instance fields to be enumerated.
         foreach (FieldInfo fi in m_current.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)) {
            Schedule(fi.GetValue(m_current));
         }
      }
      return true;
   }

   // Returns true if the object has no data fields with information of interest.
   private Boolean IsTerminalObject(Object data) {
      Type t = data.GetType();
      return t.IsPrimitive || t.IsEnum || t.IsPointer || data is String;
   }
}

public sealed class App {
   // Define some fields in the class to test the ObjectWalker.
   public String name = "Fred";
   public Int32 Age = 40;

   static void Main() {
      // Build an object graph using an array that refers to various objects.
      Object[] data = new Object[] { "Jeff", 123, 555L, (Byte) 35, new App() };

      // Construct an ObjectWalker and pass it the root of the object graph.
      ObjectWalker ow = new ObjectWalker(data);

      // Enumerate all of the objects in the graph and count the number of objects.
      Int64 num = 0;
      foreach (Object o in ow) {
         // Display each object's type and value as a string.
         Console.WriteLine("Object #{0}: Type={1}, Value's string={2}",
            num++, o.GetType(), o.ToString());
      }
   }
}

// This code produces the following output.
//
// Object #0: Type=App, Value's string=App
// Object #1: Type=System.Int32, Value's string=40
// Object #2: Type=System.String, Value's string=Fred
// Object #3: Type=System.Byte, Value's string=35
// Object #4: Type=System.Int64, Value's string=555
// Object #5: Type=System.Int32, Value's string=123
// Object #6: Type=System.String, Value's string=Jeff

Comentarios

Durante la deserialización, consulta FormatterObjectManager el objeto para determinar si una referencia a un objeto de la secuencia serializada hace referencia a un objeto que ya se ha deserializado (una referencia hacia atrás) o a un objeto que aún no se ha deserializado (una referencia hacia delante). Si la referencia de la secuencia serializada es una referencia hacia delante, Formatter puede registrar una corrección con .ObjectManager Si la referencia de la secuencia serializada es una referencia hacia atrás, Formatter finaliza inmediatamente la referencia. La corrección hace referencia al proceso de finalización de referencias de objeto no completadas durante el proceso de deserialización de objetos. Una vez deserializado el objeto necesario, ObjectManager completará la referencia.

ObjectManager Sigue un conjunto de reglas que dictan el orden de corrección. Todos los objetos que implementan ISerializable o tienen un ISerializationSurrogate pueden esperar tener todos los objetos que transmiten a través SerializationInfo de disponibles cuando se deserializa el árbol de objetos. Sin embargo, un objeto primario no puede suponer que todos sus objetos secundarios se completarán completamente cuando esté completamente deserializado. Todos los objetos secundarios estarán presentes, pero no todos los objetos secundarios estarán necesariamente presentes. Si un objeto necesita realizar determinadas acciones que dependen de la ejecución de código en sus objetos secundarios, puede retrasar estas acciones, implementar la IDeserializationCallback interfaz y ejecutar el código solo cuando se llama de nuevo en esta interfaz.

Constructores

ObjectManager(ISurrogateSelector, StreamingContext)
Obsoletos.

Inicializa una nueva instancia de la clase ObjectManager.

Métodos

DoFixups()
Obsoletos.

Realiza todas las correcciones registradas.

Equals(Object)
Obsoletos.

Determina si el objeto especificado es igual que el objeto actual.

(Heredado de Object)
GetHashCode()
Obsoletos.

Sirve como la función hash predeterminada.

(Heredado de Object)
GetObject(Int64)
Obsoletos.

Devuelve el objeto que tiene el identificador de objeto especificado.

GetType()
Obsoletos.

Obtiene el Type de la instancia actual.

(Heredado de Object)
MemberwiseClone()
Obsoletos.

Crea una copia superficial del Object actual.

(Heredado de Object)
RaiseDeserializationEvent()
Obsoletos.

Provoca el evento de deserialización para cualquier objeto registrado que implemente IDeserializationCallback.

RaiseOnDeserializingEvent(Object)
Obsoletos.

Invoca el método marcado con OnDeserializingAttribute.

RecordArrayElementFixup(Int64, Int32, Int64)
Obsoletos.

Registra una corrección para un elemento de una matriz.

RecordArrayElementFixup(Int64, Int32[], Int64)
Obsoletos.

Registra correcciones para los elementos especificados de una matriz que se ejecutarán más adelante.

RecordDelayedFixup(Int64, String, Int64)
Obsoletos.

Registra una corrección para un miembro de objeto que se ejecutará más adelante.

RecordFixup(Int64, MemberInfo, Int64)
Obsoletos.

Registra una corrección para un miembro de un objeto que se ejecutará más adelante.

RegisterObject(Object, Int64)
Obsoletos.

Registra un objeto cuando se deserializa y lo asocia a objectID.

RegisterObject(Object, Int64, SerializationInfo)
Obsoletos.

Registra un objeto cuando se deserializa, lo asocia a objectID y registra el objeto SerializationInfo que se utilizó con el mismo.

RegisterObject(Object, Int64, SerializationInfo, Int64, MemberInfo)
Obsoletos.

Registra un miembro de un objeto cuando se deserializa, lo asocia a objectID y registra SerializationInfo.

RegisterObject(Object, Int64, SerializationInfo, Int64, MemberInfo, Int32[])
Obsoletos.

Registra un miembro de una matriz incluida en un objeto mientras se deserializa, lo asocia a objectID y registra SerializationInfo.

ToString()
Obsoletos.

Devuelve una cadena que representa el objeto actual.

(Heredado de Object)

Se aplica a