Evaluar y enviar comentarios
Contraer todo/Expandir todo Contraer todo
Esta página es específica de
Microsoft Visual Studio 2005/.NET Framework 2.0

Hay además otras versiones disponibles para:
Biblioteca de clases de .NET Framework
OnDeserializingAttribute (Clase)

Nota: esta clase es nueva en la versión 2.0 de .NET Framework.

Cuando se aplica a un método, especifica que la llamada al método se produce durante la deserialización de un objeto.

Espacio de nombres: System.Runtime.Serialization
Ensamblado: mscorlib (en mscorlib.dll)

Visual Basic (Declaración)
<ComVisibleAttribute(True)> _
<AttributeUsageAttribute(AttributeTargets.Method, Inherited:=False)> _
Public NotInheritable Class OnDeserializingAttribute
    Inherits Attribute
Visual Basic (Uso)
Dim instance As OnDeserializingAttribute
C#
[ComVisibleAttribute(true)] 
[AttributeUsageAttribute(AttributeTargets.Method, Inherited=false)] 
public sealed class OnDeserializingAttribute : Attribute
C++
[ComVisibleAttribute(true)] 
[AttributeUsageAttribute(AttributeTargets::Method, Inherited=false)] 
public ref class OnDeserializingAttribute sealed : public Attribute
J#
/** @attribute ComVisibleAttribute(true) */ 
/** @attribute AttributeUsageAttribute(AttributeTargets.Method, Inherited=false) */ 
public final class OnDeserializingAttribute extends Attribute
JScript
ComVisibleAttribute(true) 
AttributeUsageAttribute(AttributeTargets.Method, Inherited=false) 
public final class OnDeserializingAttribute extends Attribute

Utilice OnDeserializingAttribute para establecer los valores predeterminados durante la deserialización. Por ejemplo, si el tipo que está deserializando no contiene ningún constructor, cree un método para establecer valores de cualquier campo de la instancia y aplique el atributo al método.

Para utilizar OnDeserializingAttribute, el método debe contener un parámetro StreamingContext. El atributo marca el método al que llamará la infraestructura de la serialización y StreamingContext proporciona datos adicionales sobre el tipo de serialización que va a tener lugar. En el código siguiente se muestra su utilización:

C#
\\ C#
[OnDeserializingAttribute()]
internal void RunThisMethod(StreamingContext context)
{ 
    // Code not shown.
}
' Visual Basic
<OnDeserializingAttribute()> _
Private Sub RunThisMethod(context As StreamingContext)
    ' Code not shown.
End Sub
NotaNota

En el código, se puede utilizar la palabra OnDeserializing en lugar de OnDeserializingAttribute, que resulta más largo.

En el ejemplo siguiente se aplican los atributos OnDeserializedAttribute, OnSerializingAttribute, OnSerializedAttribute y OnDeserializingAttribute a los métodos de una clase.

Visual Basic
Imports System
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 "data.xml" 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()
        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.'
C#
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 "data.xml" 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();
        }
        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.'
System.Object
   System.Attribute
    System.Runtime.Serialization.OnDeserializingAttribute
Los miembros estáticos públicos (Shared en Visual Basic) de este tipo son seguros para la ejecución de subprocesos. No se garantiza que los miembros de instancias sean seguros para la ejecución de subprocesos.

Windows 98, Windows 2000 SP4, Windows Millennium, Windows Server 2003, Windows XP Media Center, Windows XP Professional x64, Windows XP SP2, Windows XP Starter Edition

.NET Framework no admite todas las versiones de cada plataforma. Para obtener una lista de las versiones admitidas, vea Requisitos del sistema.

.NET Framework

Compatible con: 2.0
Contenido de la comunidad   ¿Qué es Community Content?
Agregar contenido nuevo RSS  Anotaciones
Processing
© 2012 Microsoft. Reservados todos los derechos. Términos de uso | Marcas Registradas | Privacidad
Page view tracker