OnSerializingAttribute Classe

Definição

Quando aplicado a um método, especifica que o método é chamado durante a serialização de um objeto em um grafo de objeto. A ordem de serialização em relação a outros objetos no gráfico é não determinística.

public ref class OnSerializingAttribute sealed : Attribute
[System.AttributeUsage(System.AttributeTargets.Method, Inherited=false)]
public sealed class OnSerializingAttribute : Attribute
[System.AttributeUsage(System.AttributeTargets.Method, Inherited=false)]
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class OnSerializingAttribute : Attribute
[<System.AttributeUsage(System.AttributeTargets.Method, Inherited=false)>]
type OnSerializingAttribute = class
    inherit Attribute
[<System.AttributeUsage(System.AttributeTargets.Method, Inherited=false)>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type OnSerializingAttribute = class
    inherit Attribute
Public NotInheritable Class OnSerializingAttribute
Inherits Attribute
Herança
OnSerializingAttribute
Atributos

Exemplos

O exemplo a seguir aplica os OnDeserializedAttributeatributos e , OnSerializingAttributeOnSerializedAttributee OnDeserializingAttribute os métodos em uma classe.

using System;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

public class Test
{
    public static void Main()
    {
        // Create a new TestSimpleObject object.
        TestSimpleObject obj = new TestSimpleObject();

        Console.WriteLine("\n Before serialization the object contains: ");
        obj.Print();

        // Open a file and serialize the object into binary format.
        Stream stream = File.Open("DataFile.dat", FileMode.Create);
        BinaryFormatter formatter = new BinaryFormatter();

        try
        {
            formatter.Serialize(stream, obj);

            // Print the object again to see the effect of the 
            //OnSerializedAttribute.
            Console.WriteLine("\n After serialization the object contains: ");
            obj.Print();

            // Set the original variable to null.
            obj = null;
            stream.Close();

            // Open the file "DataFile.dat" and deserialize the object from it.
            stream = File.Open("DataFile.dat", FileMode.Open);

            // Deserialize the object from the data file.
            obj = (TestSimpleObject)formatter.Deserialize(stream);

            Console.WriteLine("\n After deserialization the object contains: ");
            obj.Print();
            Console.ReadLine();
        }
        catch (SerializationException se)
        {
            Console.WriteLine("Failed to serialize. Reason: " + se.Message);
            throw;
        }
        catch (Exception exc)
        {
            Console.WriteLine("An exception occurred. Reason: " + exc.Message);
            throw;
        }
        finally
        {
            stream.Close();
            obj = null;
            formatter = null;
        }
    }
}

// This is the object that will be serialized and deserialized.
[Serializable()]
public class TestSimpleObject
{
    // This member is serialized and deserialized with no change.
    public int member1;

    // The value of this field is set and reset during and 
    // after serialization.
    private string member2;

    // This field is not serialized. The OnDeserializedAttribute 
    // is used to set the member value after serialization.
    [NonSerialized()]
    public string member3;

    // This field is set to null, but populated after deserialization.
    private string member4;

    // Constructor for the class.
    public TestSimpleObject()
    {
        member1 = 11;
        member2 = "Hello World!";
        member3 = "This is a nonserialized value";
        member4 = null;
    }

    public void Print()
    {
        Console.WriteLine("member1 = '{0}'", member1);
        Console.WriteLine("member2 = '{0}'", member2);
        Console.WriteLine("member3 = '{0}'", member3);
        Console.WriteLine("member4 = '{0}'", member4);
    }

    [OnSerializing()]
    internal void OnSerializingMethod(StreamingContext context)
    {
        member2 = "This value went into the data file during serialization.";
    }

    [OnSerialized()]
    internal void OnSerializedMethod(StreamingContext context)
    {
        member2 = "This value was reset after serialization.";
    }

    [OnDeserializing()]
    internal void OnDeserializingMethod(StreamingContext context)
    {
        member3 = "This value was set during deserialization";
    }

    [OnDeserialized()]
    internal void OnDeserializedMethod(StreamingContext context)
    {
        member4 = "This value was set after deserialization.";
    }
}

// Output:
//  Before serialization the object contains: 
// member1 = '11'
// member2 = 'Hello World!'
// member3 = 'This is a nonserialized value'
// member4 = ''
//
//  After serialization the object contains: 
// member1 = '11'
// member2 = 'This value was reset after serialization.'
// member3 = 'This is a nonserialized value'
// member4 = ''
//
//  After deserialization the object contains: 
// member1 = '11'
// member2 = 'This value went into the data file during serialization.'
// member3 = 'This value was set during deserialization'
// member4 = 'This value was set after deserialization.'
Imports System.IO
Imports System.Runtime.Serialization
Imports System.Runtime.Serialization.Formatters.Binary

Public Class Test
    Public Shared Sub Main()
        ' Create a new TestSimpleObject object.
        Dim obj As New TestSimpleObject()

        Console.WriteLine(vbLf + " Before serialization the object contains: ")
        obj.Print()

        ' Open a file and serialize the object into binary format.
        Dim stream As Stream = File.Open("DataFile.dat", FileMode.Create)
        Dim formatter As New BinaryFormatter()

        Try
            formatter.Serialize(stream, obj)

            ' Print the object again to see the effect of the 
            'OnSerializedAttribute.
            Console.WriteLine(vbLf + " After serialization the object contains: ")
            obj.Print()

            ' Set the original variable to null.
            obj = Nothing
            stream.Close()

            ' Open the file "DataFile.dat" and deserialize the object from it.
            stream = File.Open("DataFile.dat", FileMode.Open)

            ' Deserialize the object from the data file.
            obj = CType(formatter.Deserialize(stream), TestSimpleObject)

            Console.WriteLine(vbLf + " After deserialization the object contains: ")
            obj.Print()
            Console.ReadLine()
        Catch se As SerializationException
            Console.WriteLine("Failed to serialize. Reason: " + se.Message)
            Throw
        Catch exc As Exception
            Console.WriteLine("An exception occurred. Reason: " + exc.Message)
            Throw
        Finally
            stream.Close()
            obj = Nothing
            formatter = Nothing
        End Try
    End Sub
End Class


' This is the object that will be serialized and deserialized.
<Serializable()> _
Public Class TestSimpleObject
    ' This member is serialized and deserialized with no change.
    Public member1 As Integer

    ' The value of this field is set and reset during and 
    ' after serialization.
    Private member2 As String

    ' This field is not serialized. The OnDeserializedAttribute 
    ' is used to set the member value after serialization.
    <NonSerialized()> _
    Public member3 As String

    ' This field is set to null, but populated after deserialization.
    Private member4 As String

    ' Constructor for the class.
    Public Sub New()
        member1 = 11
        member2 = "Hello World!"
        member3 = "This is a nonserialized value"
        member4 = Nothing
    End Sub

    Public Sub Print()
        Console.WriteLine("member1 = '{0}'", member1)
        Console.WriteLine("member2 = '{0}'", member2)
        Console.WriteLine("member3 = '{0}'", member3)
        Console.WriteLine("member4 = '{0}'", member4)
    End Sub

    <OnSerializing()> _
    Friend Sub OnSerializingMethod(ByVal context As StreamingContext)
        member2 = "This value went into the data file during serialization."
    End Sub

    <OnSerialized()> _
    Friend Sub OnSerializedMethod(ByVal context As StreamingContext)
        member2 = "This value was reset after serialization."
    End Sub

    <OnDeserializing()> _
    Friend Sub OnDeserializingMethod(ByVal context As StreamingContext)
        member3 = "This value was set during deserialization"
    End Sub

    <OnDeserialized()> _
    Friend Sub OnDeserializedMethod(ByVal context As StreamingContext)
        member4 = "This value was set after deserialization."
    End Sub
End Class

' Output:
'  Before serialization the object contains: 
' member1 = '11'
' member2 = 'Hello World!'
' member3 = 'This is a nonserialized value'
' member4 = ''
'
'  After serialization the object contains: 
' member1 = '11'
' member2 = 'This value was reset after serialization.'
' member3 = 'This is a nonserialized value'
' member4 = ''
'
'  After deserialization the object contains: 
' member1 = '11'
' member2 = 'This value went into the data file during serialization.'
' member3 = 'This value was set during deserialization'
' member4 = 'This value was set after deserialization.'

Comentários

Use o OnSerializingAttribute para manipular o objeto antes que a serialização ocorra.

Para usar o OnSerializingAttributemétodo, o método deve conter um StreamingContext parâmetro. O atributo marca o método a ser chamado pela infraestrutura de serialização e StreamingContext fornece dados adicionais sobre o tipo de serialização que está ocorrendo. O uso é mostrado no seguinte código:

[OnSerializing]
private void SetValuesOnSerializing(StreamingContext context)
{
    // Code not shown.
}
<OnSerializing()> _
Private Sub SetValuesOnSerializing(ByVal context As StreamingContext)
    ' Code not shown.
End Sub

Observação

Em seu código, você pode usar a palavra OnSerializing em vez da mais longa OnSerializingAttribute.

Ao usar a serialização binária, o processo de serialização binária omite a chamada ao onSerializing método quando os objetos serializados são iguais. Portanto, ao usar o BinaryFormatter tipo com o equals método (ou Object.GetHashCode) por exemplo, o resultado pode ser um comportamento indefinido.

Construtores

OnSerializingAttribute()

Inicializa uma nova instância da classe OnSerializingAttribute.

Propriedades

TypeId

Quando implementado em uma classe derivada, obtém um identificador exclusivo para este Attribute.

(Herdado de Attribute)

Métodos

Equals(Object)

Retorna um valor que indica se essa instância é igual a um objeto especificado.

(Herdado de Attribute)
GetHashCode()

Retorna o código hash para a instância.

(Herdado de Attribute)
GetType()

Obtém o Type da instância atual.

(Herdado de Object)
IsDefaultAttribute()

Quando substituído em uma classe derivada, indica se o valor dessa instância é o valor padrão para a classe derivada.

(Herdado de Attribute)
Match(Object)

Quando substituído em uma classe derivada, retorna um valor que indica se essa instância é igual a um objeto especificado.

(Herdado de Attribute)
MemberwiseClone()

Cria uma cópia superficial do Object atual.

(Herdado de Object)
ToString()

Retorna uma cadeia de caracteres que representa o objeto atual.

(Herdado de Object)

Implantações explícitas de interface

_Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

Mapeia um conjunto de nomes para um conjunto correspondente de identificadores de expedição.

(Herdado de Attribute)
_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

Recupera as informações de tipo para um objeto, que pode ser usado para obter as informações de tipo para uma interface.

(Herdado de Attribute)
_Attribute.GetTypeInfoCount(UInt32)

Retorna o número de interfaces de informações do tipo que um objeto fornece (0 ou 1).

(Herdado de Attribute)
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Fornece acesso a propriedades e métodos expostos por um objeto.

(Herdado de Attribute)

Aplica-se a

Confira também