IDataContractSurrogate.GetObjectToSerialize(Object, Type) Método

Definición

Durante la serialización, devuelve un objeto que sustituye al objeto especificado.

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

Parámetros

obj
Object

Objeto que se va a sustituir.

targetType
Type

al Type que se debe asignar el objeto sustituido.

Devoluciones

Objeto sustituido que se serializará. El objeto debe ser serializable por .DataContractSerializer Por ejemplo, debe marcarse con el DataContractAttribute atributo u otros mecanismos que reconoce el serializador.

Ejemplos

En el ejemplo siguiente se muestra una implementación del GetObjectToSerialize método .

public object GetObjectToSerialize(object obj, Type targetType)
{
        Console.WriteLine("GetObjectToSerialize Invoked");
        Console.WriteLine("\t type name: {0}", obj.ToString());
        Console.WriteLine("\t target type: {0}", targetType.Name);
        // This method is called on serialization.
        // If Person is not being serialized...
        if (obj is Person )
        {
            Console.WriteLine("\t returning PersonSurrogated");
            // ... use the XmlSerializer to perform the actual serialization.
            PersonSurrogated  ps = new PersonSurrogated();
            XmlSerializer xs = new XmlSerializer(typeof(Person));
            StringWriter sw = new StringWriter();
            xs.Serialize(sw, (Person)obj );
            ps.xmlData = sw.ToString();
            return ps;
        }
        return obj;
    }
Public Function GetObjectToSerialize(ByVal obj As Object, _
    ByVal targetType As Type) As Object _
    Implements IDataContractSurrogate.GetObjectToSerialize
    Console.WriteLine("GetObjectToSerialize Invoked")
    Console.WriteLine(vbTab & "type name: {0}", obj.ToString)
    Console.WriteLine(vbTab & "target type: {0}", targetType.Name)
    ' This method is called on serialization.
    ' If Person is not being serialized...
    If TypeOf obj Is Person Then
        Console.WriteLine(vbTab & "returning PersonSurrogated")
        ' ... use the XmlSerializer to perform the actual serialization.
        Dim ps As New PersonSurrogated()
        Dim xs As New XmlSerializer(GetType(Person))
        Dim sw As New StringWriter()
        xs.Serialize(sw, CType(obj, Person))
        ps.xmlData = sw.ToString()
        Return ps
    End If
    Return obj

End Function

Comentarios

Este método no debe devolverse null porque al deserializar los datos se convertirán en el tipo Object y se produce una InvalidCastException excepción .

Se aplica a