IDataContractSurrogate.GetDeserializedObject(Object, Type) Metodo

Definizione

Durante la deserializzazione, restituisce un oggetto che è un sostituto dell'oggetto specificato.

public:
 System::Object ^ GetDeserializedObject(System::Object ^ obj, Type ^ targetType);
public object GetDeserializedObject (object obj, Type targetType);
abstract member GetDeserializedObject : obj * Type -> obj
Public Function GetDeserializedObject (obj As Object, targetType As Type) As Object

Parametri

obj
Object

Oggetto deserializzato da sostituire.

targetType
Type

Type al quale deve essere assegnato l'oggetto sostituito.

Restituisce

Oggetto deserializzato sostituito. L'oggetto deve essere di un tipo che può essere serializzato da DataContractSerializer. Ad esempio, deve essere contrassegnato dall'attributo DataContractAttribute o tramite altri meccanismi riconosciuti dal serializzatore.

Esempio

Nel codice seguente viene illustrata un'implementazione del metodo GetDeserializedObject.

public object GetDeserializedObject(Object obj , Type targetType)
{
    Console.WriteLine("GetDeserializedObject invoked");
    // This method is called on deserialization.
    // If PersonSurrogated is being deserialized...
    if (obj is PersonSurrogated)
        {
            //... use the XmlSerializer to do the actual deserialization.
            PersonSurrogated ps = (PersonSurrogated)obj;
            XmlSerializer xs = new XmlSerializer(typeof(Person));
            return (Person)xs.Deserialize(new StringReader(ps.xmlData));
        }
        return obj;
}
Public Function GetDeserializedObject(ByVal obj As Object, _
    ByVal targetType As Type) As Object Implements _
    IDataContractSurrogate.GetDeserializedObject
    Console.WriteLine("GetDeserializedObject invoked")
    ' This method is called on deserialization.
    ' If PersonSurrogated is being deserialized...
    If TypeOf obj Is PersonSurrogated Then
        Console.WriteLine(vbTab & "returning PersonSurrogated")
        '... use the XmlSerializer to do the actual deserialization.
        Dim ps As PersonSurrogated = CType(obj, PersonSurrogated)
        Dim xs As New XmlSerializer(GetType(Person))
        Return CType(xs.Deserialize(New StringReader(ps.xmlData)), Person)
    End If
    Return obj

End Function

Commenti

In un'implementazione semplice, utilizzare una struttura di controllo If…Then…Else per verificare se il valore obj è del tipo surrogato. In questo caso, trasformare il valore appropriatamente e restituire l'oggetto sostituito. L'oggetto sostituito può essere una nuova istanza o la stessa istanza obj.

Si applica a