SerializationInfo Classe

Definição

Armazena todos os dados necessários para serializar ou desserializar um objeto. Essa classe não pode ser herdada.

public ref class SerializationInfo sealed
public sealed class SerializationInfo
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class SerializationInfo
type SerializationInfo = class
[<System.Runtime.InteropServices.ComVisible(true)>]
type SerializationInfo = class
Public NotInheritable Class SerializationInfo
Herança
SerializationInfo
Atributos

Exemplos

O exemplo de código a seguir demonstra a SerializationInfo serialização personalizada e a desserialização de vários valores.

using namespace System;
using namespace System::IO;
using namespace System::Collections;
using namespace System::Runtime::Serialization::Formatters::Binary;
using namespace System::Runtime::Serialization;

ref class SingletonSerializationHelper;

// There should be only one instance of this type per AppDomain.

[Serializable]
public ref class Singleton sealed: public ISerializable
{
private:

   // This is the one instance of this type.
   static Singleton^ theOneObject = gcnew Singleton;

public:

   // Here are the instance fields.
   String^ someString;
   Int32 someNumber;

private:

   // Private constructor allowing this type to construct the singleton.
   Singleton()
   {
      
      // Do whatever is necessary to initialize the singleton.
      someString = "This is a String* field";
      someNumber = 123;
   }

public:

   // A method returning a reference to the singleton.
   static Singleton^ GetSingleton()
   {
      return theOneObject;
   }

   // A method called when serializing a Singleton.
   [System::Security::Permissions::SecurityPermissionAttribute
   (System::Security::Permissions::SecurityAction::LinkDemand, 
   Flags=System::Security::Permissions::SecurityPermissionFlag::SerializationFormatter)]
   virtual void GetObjectData( SerializationInfo^ info, StreamingContext context )
   {
      // Instead of serializing this Object*, we will  
      // serialize a SingletonSerializationHelp instead.
      info->SetType( SingletonSerializationHelper::typeid );

      // No other values need to be added.
   }

   // NOTE: ISerializable*'s special constructor is NOT necessary 
   // because it's never called
};

[Serializable]
private ref class SingletonSerializationHelper sealed: public IObjectReference
{
public:

   // This Object* has no fields (although it could).
   // GetRealObject is called after this Object* is deserialized
   virtual Object^ GetRealObject( StreamingContext context )
   {
      // When deserialiing this Object*, return a reference to 
      // the singleton Object* instead.
      return Singleton::GetSingleton();
   }
};

[STAThread]
int main()
{
   FileStream^ fs = gcnew FileStream( "DataFile.dat",FileMode::Create );
   try
   {
      // Construct a BinaryFormatter and use it 
      // to serialize the data to the stream.
      BinaryFormatter^ formatter = gcnew BinaryFormatter;

      // Create an array with multiple elements refering to 
      // the one Singleton Object*.
      array<Singleton^>^a1 = {Singleton::GetSingleton(),Singleton::GetSingleton()};

      // This displays S"True".
      Console::WriteLine( "Do both array elements refer to the same Object? {0}", (a1[ 0 ] == a1[ 1 ]) );

      // Serialize the array elements.
      formatter->Serialize( fs, a1 );

      // Deserialize the array elements.
      fs->Position = 0;
      array<Singleton^>^a2 = (array<Singleton^>^)formatter->Deserialize( fs );

      // This displays S"True".
      Console::WriteLine( "Do both array elements refer to the same Object? {0}", (a2[ 0 ] == a2[ 1 ]) );

      // This displays S"True".
      Console::WriteLine( "Do all  array elements refer to the same Object? {0}", (a1[ 0 ] == a2[ 0 ]) );
   }
   catch ( SerializationException^ e ) 
   {
      Console::WriteLine( "Failed to serialize. Reason: {0}", e->Message );
      throw;
   }
   finally
   {
      fs->Close();
   }

   return 0;
}
using System;
using System.Text;
using System.IO;
// Add references to Soap and Binary formatters.
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization.Formatters.Soap ;
using System.Runtime.Serialization;

[Serializable]
public class MyItemType : ISerializable
{
    public MyItemType()
    {
        // Empty constructor required to compile.
    }

    // The value to serialize.
    private string myProperty_value;

    public string MyProperty
    {
        get { return myProperty_value; }
        set { myProperty_value = value; }
    }

    // Implement this method to serialize data. The method is called
    // on serialization.
    public void GetObjectData(SerializationInfo info, StreamingContext context)
    {
        // Use the AddValue method to specify serialized values.
        info.AddValue("props", myProperty_value, typeof(string));
    }

    // The special constructor is used to deserialize values.
    public MyItemType(SerializationInfo info, StreamingContext context)
    {
        // Reset the property value using the GetValue method.
        myProperty_value = (string) info.GetValue("props", typeof(string));
    }
}

// This is a console application.
public static class Test
{
    static void Main()
    {
        // This is the name of the file holding the data. You can use any file extension you like.
        string fileName = "dataStuff.myData";

        // Use a BinaryFormatter or SoapFormatter.
        IFormatter formatter = new BinaryFormatter();
        //IFormatter formatter = new SoapFormatter();

        Test.SerializeItem(fileName, formatter); // Serialize an instance of the class.
        Test.DeserializeItem(fileName, formatter); // Deserialize the instance.
        Console.WriteLine("Done");
        Console.ReadLine();
    }

    public static void SerializeItem(string fileName, IFormatter formatter)
    {
        // Create an instance of the type and serialize it.
        MyItemType t = new MyItemType();
        t.MyProperty = "Hello World";

        FileStream s = new FileStream(fileName , FileMode.Create);
        formatter.Serialize(s, t);
        s.Close();
    }

    public static void DeserializeItem(string fileName, IFormatter formatter)
    {
        FileStream s = new FileStream(fileName, FileMode.Open);
        MyItemType t = (MyItemType)formatter.Deserialize(s);
        Console.WriteLine(t.MyProperty);
    }
}
Imports System.Text
Imports System.IO

' Add references to Soap and Binary formatters.
Imports System.Runtime.Serialization.Formatters.Binary
Imports System.Runtime.Serialization.Formatters.Soap
Imports System.Runtime.Serialization


<Serializable()> _
Public Class MyItemType
    Implements ISerializable
    ' Empty constructor required to compile.
    Public Sub New()
    End Sub

    ' The value to serialize.
    Private myProperty_value As String

    Public Property MyProperty() As String
        Get
            Return myProperty_value
        End Get
        Set(value As String)
            myProperty_value = value
        End Set
    End Property

    ' Implement this method to serialize data. The method is called 
    ' on serialization.
    Public Sub GetObjectData(info As SerializationInfo, context As StreamingContext) Implements ISerializable.GetObjectData
        ' Use the AddValue method to specify serialized values.
        info.AddValue("props", myProperty_value, GetType(String))

    End Sub

    ' The special constructor is used to deserialize values.
    Public Sub New(info As SerializationInfo, context As StreamingContext)
        ' Reset the property value using the GetValue method.
        myProperty_value = DirectCast(info.GetValue("props", GetType(String)), String)
    End Sub
End Class

' This is a console application. 
Public Class Test


    Public Shared Sub Main()
        ' This is the name of the file holding the data. You can use any file extension you like.
        Dim fileName As String = "dataStuff.myData"

        ' Use a BinaryFormatter or SoapFormatter.
        Dim formatter As IFormatter = New BinaryFormatter()
        ' Dim formatter As IFormatter = New SoapFormatter()

        Test.SerializeItem(fileName, formatter)
        ' Serialize an instance of the class.
        Test.DeserializeItem(fileName, formatter)
        ' Deserialize the instance.
        Console.WriteLine("Done")
        Console.ReadLine()
    End Sub

    Public Shared Sub SerializeItem(fileName As String, formatter As IFormatter)
        ' Create an instance of the type and serialize it.
        Dim myType As New MyItemType()
        myType.MyProperty = "Hello World"

        Dim fs As New FileStream(fileName, FileMode.Create)
        formatter.Serialize(fs, myType)
        fs.Close()
    End Sub


    Public Shared Sub DeserializeItem(fileName As String, formatter As IFormatter)
        Dim fs As New FileStream(fileName, FileMode.Open)

        Dim myType As MyItemType = DirectCast(formatter.Deserialize(fs), MyItemType)
        Console.WriteLine(myType.MyProperty)
    End Sub
End Class

Comentários

Essa classe é usada por objetos com comportamento de serialização personalizado. O GetObjectData método no repositório ISerializable ou ISerializationSurrogate popula o SerializationInfo repositório com o nome, o tipo e o valor de cada informação que deseja serializar. Durante a desserialização, a função apropriada pode extrair essas informações.

Os objetos são adicionados ao SerializationInfo repositório em tempo de serialização usando os AddValue métodos e extraídos do SerializationInfo repositório na desserialização usando os GetValue métodos.

Para obter mais informações sobre como personalizar a serialização, consulte Serialização Personalizada.

Construtores

SerializationInfo(Type, IFormatterConverter)

Cria uma nova instância da classe SerializationInfo.

SerializationInfo(Type, IFormatterConverter, Boolean)

Inicializa uma nova instância da classe SerializationInfo.

Propriedades

AssemblyName

Obtém ou define o nome do assembly do tipo a ser serializado durante a serialização somente.

FullTypeName

Obtém ou define o nome completo do Type a ser serializado.

IsAssemblyNameSetExplicit

Obtém se o nome do assembly foi explicitamente definido.

IsFullTypeNameSetExplicit

Obtém se o nome completo do tipo foi explicitamente definido.

MemberCount

Obtém o número de membros que foram adicionados ao repositório SerializationInfo.

ObjectType

Retorna o tipo do objeto a ser serializado.

Métodos

AddValue(String, Boolean)

Adiciona um valor booliano ao repositório SerializationInfo.

AddValue(String, Byte)

Adiciona um valor inteiro sem sinal de 8 bits ao repositório SerializationInfo.

AddValue(String, Char)

Adiciona um valor de caractere Unicode ao repositório SerializationInfo.

AddValue(String, DateTime)

Adiciona um valor DateTime ao repositório SerializationInfo.

AddValue(String, Decimal)

Adiciona um valor decimal ao repositório SerializationInfo.

AddValue(String, Double)

Adiciona um valor de ponto flutuante de precisão dupla ao repositório SerializationInfo.

AddValue(String, Int16)

Adiciona um valor inteiro com sinal de 16 bits ao repositório SerializationInfo.

AddValue(String, Int32)

Adiciona um valor inteiro com sinal de 32 bits ao repositório SerializationInfo.

AddValue(String, Int64)

Adiciona um valor inteiro com sinal de 64 bits ao repositório SerializationInfo.

AddValue(String, Object)

Adiciona o objeto especificado ao repositório SerializationInfo, no qual ele é associado a um nome especificado.

AddValue(String, Object, Type)

Adiciona um valor ao repositório SerializationInfo, em que value é associado ao name e é serializado como sendo do Typetype.

AddValue(String, SByte)

Adiciona um valor inteiro com sinal de 8 bits ao repositório SerializationInfo.

AddValue(String, Single)

Adiciona um valor de ponto flutuante de precisão simples ao repositório SerializationInfo.

AddValue(String, UInt16)

Adiciona um valor inteiro sem sinal de 16 bits ao repositório SerializationInfo.

AddValue(String, UInt32)

Adiciona um valor inteiro sem sinal de 32 bits ao repositório SerializationInfo.

AddValue(String, UInt64)

Adiciona um valor inteiro sem sinal de 64 bits ao repositório SerializationInfo.

Equals(Object)

Determina se o objeto especificado é igual ao objeto atual.

(Herdado de Object)
GetBoolean(String)

Recupera um valor booliano do repositório do SerializationInfo.

GetByte(String)

Recupera um valor inteiro sem sinal de 8 bits do repositório SerializationInfo.

GetChar(String)

Recupera um valor de caractere Unicode do repositório SerializationInfo.

GetDateTime(String)

Recupera um valor DateTime do repositório SerializationInfo.

GetDecimal(String)

Recupera um valor decimal do repositório SerializationInfo.

GetDouble(String)

Recupera um valor de ponto flutuante de precisão dupla do repositório SerializationInfo.

GetEnumerator()

Retorna um SerializationInfoEnumerator usado para iterar por meio dos pares nome-valor no repositório SerializationInfo.

GetHashCode()

Serve como a função de hash padrão.

(Herdado de Object)
GetInt16(String)

Recupera um valor inteiro com sinal de 16 bits do repositório SerializationInfo.

GetInt32(String)

Recupera um valor inteiro com sinal de 32 bits do repositório SerializationInfo.

GetInt64(String)

Recupera um valor inteiro com sinal de 64 bits do repositório SerializationInfo.

GetSByte(String)

Recupera um valor inteiro com sinal de 8 bits do repositório SerializationInfo.

GetSingle(String)

Recupera um valor de ponto flutuante de precisão simples do repositório SerializationInfo.

GetString(String)

Recupera um valor String do repositório SerializationInfo.

GetType()

Obtém o Type da instância atual.

(Herdado de Object)
GetUInt16(String)

Recupera um valor inteiro sem sinal de 16 bits do repositório SerializationInfo.

GetUInt32(String)

Recupera um valor inteiro sem sinal de 32 bits do repositório SerializationInfo.

GetUInt64(String)

Recupera um valor inteiro sem sinal de 64 bits do repositório SerializationInfo.

GetValue(String, Type)

Recupera um valor do repositório do SerializationInfo.

MemberwiseClone()

Cria uma cópia superficial do Object atual.

(Herdado de Object)
SetType(Type)

Define o Type do objeto a ser serializado.

ToString()

Retorna uma cadeia de caracteres que representa o objeto atual.

(Herdado de Object)

Aplica-se a

Confira também