SerializeObjectState Evento
Collapse the table of content
Expand the table of content
Este artículo se tradujo automáticamente. Para ver el artículo en inglés, active la casilla Inglés. Además, puede mostrar el texto en inglés en una ventana emergente si mueve el puntero del mouse sobre el texto.

Exception.SerializeObjectState (Evento)

.NET Framework (current version)

Ocurre cuando una excepción se serializa para crear un objeto de estado de excepción que contenga datos serializados sobre la excepción.

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

protected event EventHandler<SafeSerializationEventArgs> SerializeObjectState

The exception state object implements the T:System.Runtime.Serialization.ISafeSerializationData interface.

When the E:System.Exception.SerializeObjectState event is subscribed to, the exception is deserialized and created as an empty exception. The exception's constructor is not run, and the exception state is also deserialized. The M:System.Runtime.Serialization.ISafeSerializationData.CompleteDeserialization(System.Object) callback method of the exception state object is then notified so that it can push deserialized data into the empty exception.

The E:System.Exception.SerializeObjectState event enables transparent exception types to serialize and deserialize exception data. Transparent code can execute commands within the bounds of the permission set it is operating within, but cannot execute, call, derive from, or contain critical code.

If the E:System.Exception.SerializeObjectState event is not subscribed to, deserialization occurs as usual using the M:System.Exception.#ctor(System.Runtime.Serialization.SerializationInfo,System.Runtime.Serialization.StreamingContext) constructor.

Typically, a handler for the E:System.Exception.SerializeObjectState event is added in the exception's constructor to provide for its serialization. But because the constructor is not executed when the E:System.Exception.SerializeObjectState event handler executes, serializing a deserialized exception can throw a T:System.Runtime.Serialization.SerializationException exception when you try to deserialize the exception. To avoid this, you should also add the handler for the E:System.Exception.SerializeObjectState event in the M:System.Runtime.Serialization.ISafeSerializationData.CompleteDeserialization(System.Object) method. See the Examples section for an illustration.

Notas para los implementadores:

If this event is subscribed to and used, all derived types that follow in the inheritance hierarchy must implement the same serialization mechanism.

The following example defines a BadDivisionException that handles the E:System.Exception.SerializeObjectState event. It also contains a state object, which is a nested structure named BadDivisionExceptionState that implements the T:System.Runtime.Serialization.ISafeSerializationData interface.

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

public class Example
   public static void Main()
      bool serialized = false;
      var formatter = new BinaryFormatter();
      Double[] values = { 3, 2, 1 };
      Double divisor = 0;
      foreach (var value in values) {
         try {
            BadDivisionException ex = null;
            if (divisor == 0) { 
               if (! serialized) {
                  // Instantiate the exception object.
                  ex = new BadDivisionException(0);
                  // Serialize the exception object.
                  var fs = new FileStream("BadDivision1.dat", 
                  formatter.Serialize(fs, ex);
                  Console.WriteLine("Serialized the exception...");
               else {
                  // Deserialize the exception.
                  var fs = new FileStream("BadDivision1.dat",
                  ex = (BadDivisionException) formatter.Deserialize(fs);
                  // Reserialize the exception.
                  fs.Position = 0;
                  formatter.Serialize(fs, ex);
                  Console.WriteLine("Reserialized the exception...");                                            
              throw ex; 
            Console.WriteLine("{0} / {1} = {1}", value, divisor, value/divisor);
         catch (BadDivisionException e) {
            Console.WriteLine("Bad divisor from a {0} exception: {1}",
                              serialized ? "deserialized" : "new", e.Divisor);             
            serialized = true;

[Serializable] public class BadDivisionException : Exception
   // Maintain an internal BadDivisionException state object.
   [NonSerialized] private BadDivisionExceptionState state = new BadDivisionExceptionState();

   public BadDivisionException(Double divisor)
      state.Divisor = divisor;

   private void HandleSerialization()
      SerializeObjectState += delegate(object exception, SafeSerializationEventArgs eventArgs) 

   public Double Divisor
   { get { return state.Divisor; } }

   [Serializable] private struct BadDivisionExceptionState : ISafeSerializationData 
      private Double badDivisor;

      public Double Divisor
      { get { return badDivisor; } 
        set { badDivisor = value; } }

      void ISafeSerializationData.CompleteDeserialization(object deserialized)
         var ex = deserialized as BadDivisionException;
         ex.state = this; 
// The example displays the following output:
//       Serialized the exception...
//       Bad divisor from a new exception: 0
//       Reserialized the exception...
//       Bad divisor from a deserialized exception: 0
//       Reserialized the exception...
//       Bad divisor from a deserialized exception: 0

The BadDivisionException exception is thrown when a floating-point division by zero occurs. During the first division by zero, the example instantiates a BadDivisionException object, serializes it, and throws the exception. When subsequent divisions by zero occur, the example deserializes the previously serialized object, reserializes it, and throws the exception. To provide for object serialization, deserialization, reserialization, and deserialization, the example adds the E:System.Exception.SerializeObjectState event handler both in the BadDivisionException class constructor and in the M:System.Runtime.Serialization.ISafeSerializationData.CompleteDeserialization(System.Object) implementation.

.NET Framework
Disponible desde 4.0
Volver al principio
© 2016 Microsoft