ObjectManager Classe
Definição
Importante
Algumas informações dizem respeito a um produto pré-lançado que pode ser substancialmente modificado antes de ser lançado. A Microsoft não faz garantias, de forma expressa ou implícita, em relação à informação aqui apresentada.
Mantém o registo dos objetos à medida que são desserializados.
public ref class ObjectManager
public class ObjectManager
[System.Runtime.InteropServices.ComVisible(true)]
public class ObjectManager
type ObjectManager = class
[<System.Runtime.InteropServices.ComVisible(true)>]
type ObjectManager = class
Public Class ObjectManager
- Herança
-
ObjectManager
- Atributos
Exemplos
O exemplo de código seguinte mostra como usar a ObjectManager classe para percorrer um grafo de objetos, percorrendo cada objeto apenas uma 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
Observações
Durante a desserialização, as Formatter consultas servem ObjectManager para determinar se uma referência a um objeto no fluxo serializado se refere a um objeto que já foi desserializado (uma referência retroativa), ou a um objeto que ainda não foi desserializado (uma referência direta). Se a referência no fluxo serializado for uma referência direta, então pode Formatter registar uma fixup com o ObjectManager. Se a referência no fluxo serializado for uma referência retroativa, a Formatter referência completa imediatamente. Fixup refere-se ao processo de finalização de referências a objetos que ainda não foram concluídas durante o processo de desserialização de objetos. Depois de o objeto requerido ter sido desserializado, a ObjectManager referência será completada.
Segue-se ObjectManager um conjunto de regras que ditam a ordem de fixup. Todos os objetos que implementam ISerializable ou têm um ISerializationSurrogate podem esperar ter todos os objetos através SerializationInfo dos quais transmitiram disponíveis quando a árvore de objetos for desserializada. No entanto, um objeto pai não pode presumir que todos os seus objetos filhos estarão totalmente concluídos quando estiver totalmente desserializado. Todos os objetos filhos estarão presentes, mas nem todos os objetos netos estarão necessariamente presentes. Se um objeto precisar de realizar certas ações que dependem da execução de código nos seus objetos filhos, pode atrasar essas ações, implementar a IDeserializationCallback interface e executar o código apenas quando for chamado de volta nessa interface.
Construtores
| Name | Description |
|---|---|
| ObjectManager(ISurrogateSelector, StreamingContext) |
Inicializa uma nova instância da ObjectManager classe. |
Métodos
| Name | Description |
|---|---|
| DoFixups() |
Executa todas as reparações gravadas. |
| Equals(Object) |
Determina se o objeto especificado é igual ao objeto atual. (Herdado de Object) |
| GetHashCode() |
Serve como função de hash predefinida. (Herdado de Object) |
| GetObject(Int64) |
Devolve o objeto com o ID especificado. |
| GetType() |
Obtém o Type da instância atual. (Herdado de Object) |
| MemberwiseClone() |
Cria uma cópia superficial do atual Object. (Herdado de Object) |
| RaiseDeserializationEvent() |
Eleva o evento de desserialização para qualquer objeto registado que implemente IDeserializationCallback. |
| RaiseOnDeserializingEvent(Object) |
Invoca o método marcado com o OnDeserializingAttribute. |
| RecordArrayElementFixup(Int64, Int32, Int64) |
Regista uma fixup para um elemento num array. |
| RecordArrayElementFixup(Int64, Int32[], Int64) |
Regista fixups para os elementos especificados num array, para serem executados mais tarde. |
| RecordDelayedFixup(Int64, String, Int64) |
Regista uma fixup para um membro do objeto, para ser executada mais tarde. |
| RecordFixup(Int64, MemberInfo, Int64) |
Regista uma fixup para um membro de um objeto, para ser executada posteriormente. |
| RegisterObject(Object, Int64, SerializationInfo, Int64, MemberInfo, Int32[]) |
Regista um membro de um array contido num objeto enquanto este está desserializado, associando-o a |
| RegisterObject(Object, Int64, SerializationInfo, Int64, MemberInfo) |
Regista um membro de um objeto à medida que este é desserializado, associando-o a |
| RegisterObject(Object, Int64, SerializationInfo) |
Regista um objeto à medida que é desserializado, associando-o a |
| RegisterObject(Object, Int64) |
Regista um objeto à medida que é desserializado, associando-o a |
| ToString() |
Devolve uma cadeia que representa o objeto atual. (Herdado de Object) |