SerializationInfo Classe

Définition

Stocke toutes les données nécessaires pour sérialiser ou désérialiser un objet.Stores all the data needed to serialize or deserialize an object. Cette classe ne peut pas être héritée.This class cannot be inherited.

public ref class SerializationInfo sealed
[System.Runtime.InteropServices.ComVisible(true)]
public sealed class SerializationInfo
type SerializationInfo = class
Public NotInheritable Class SerializationInfo
Héritage
SerializationInfo
Attributs

Exemples

L’exemple de code suivant illustre SerializationInfo la sérialisation et la désérialisation personnalisées de différentes valeurs.The following code example demonstrates the SerializationInfo for custom serialization and deserialization of various values.

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

Remarques

Cette classe est utilisée par les objets avec un comportement de sérialisation personnalisé.This class is used by objects with custom serialization behavior. La GetObjectData méthode ISerializable sur ouISerializationSurrogate remplit leSerializationInfo magasin avec le nom, le type et la valeur de chaque élément d’information qu’il souhaite sérialiser.The GetObjectData method on either ISerializable or ISerializationSurrogate populates the SerializationInfo store with the name, type, and value of each piece of information it wants to serialize. Pendant la désérialisation, la fonction appropriée peut extraire ces informations.During deserialization, the appropriate function can extract this information.

Les objets sont ajoutés au SerializationInfo magasin au moment de la sérialisation AddValue à l’aide des SerializationInfo méthodes et extraits du magasin au moment de la GetValue désérialisation à l’aide des méthodes.Objects are added to the SerializationInfo store at serialization time using the AddValue methods and extracted from the SerializationInfo store at deserialization using the GetValue methods.

Pour plus d’informations sur la personnalisation de la sérialisation, consultez sérialisation personnalisée.For more information about customizing serialization, see Custom Serialization.

Constructeurs

SerializationInfo(Type, IFormatterConverter)

Crée une instance de la classe SerializationInfo.Creates a new instance of the SerializationInfo class.

SerializationInfo(Type, IFormatterConverter, Boolean)

Initialise une nouvelle instance de la classe SerializationInfo.Initializes a new instance of the SerializationInfo class.

Propriétés

AssemblyName

Obtient ou définit le nom d'assembly du type à sérialiser pendant la sérialisation uniquement.Gets or sets the assembly name of the type to serialize during serialization only.

FullTypeName

Obtient ou définit le nom complet de Type à sérialiser.Gets or sets the full name of the Type to serialize.

IsAssemblyNameSetExplicit

Obtient une valeur indiquant si le nom de l'assembly a été défini explicitement.Gets whether the assembly name has been explicitly set.

IsFullTypeNameSetExplicit

Obtient une valeur indiquant si le nom de type complet a été défini explicitement.Gets whether the full type name has been explicitly set.

MemberCount

Obtient le nombre de membres qui ont été ajoutés au magasin SerializationInfo.Gets the number of members that have been added to the SerializationInfo store.

ObjectType

Retourne le type de l'objet à sérialiser.Returns the type of the object to be serialized.

Méthodes

AddValue(String, Boolean)

Ajoute une valeur booléenne au magasin SerializationInfo.Adds a Boolean value into the SerializationInfo store.

AddValue(String, Byte)

Ajoute une valeur entière 8 bits non signée dans le magasin SerializationInfo.Adds an 8-bit unsigned integer value into the SerializationInfo store.

AddValue(String, Char)

Ajoute une valeur des caractères Unicode dans le magasin SerializationInfo.Adds a Unicode character value into the SerializationInfo store.

AddValue(String, DateTime)

Ajoute une valeur DateTime dans le magasin SerializationInfo.Adds a DateTime value into the SerializationInfo store.

AddValue(String, Decimal)

Ajoute une valeur décimale dans le magasin SerializationInfo.Adds a decimal value into the SerializationInfo store.

AddValue(String, Double)

Ajoute une valeur à virgule flottante double précision dans le magasin SerializationInfo.Adds a double-precision floating-point value into the SerializationInfo store.

AddValue(String, Int16)

Ajoute une valeur entière 16 bits signée dans le magasin SerializationInfo.Adds a 16-bit signed integer value into the SerializationInfo store.

AddValue(String, Int32)

Ajoute une valeur d’entier 32 bits signé dans le magasin SerializationInfo.Adds a 32-bit signed integer value into the SerializationInfo store.

AddValue(String, Int64)

Ajoute une valeur d’entier 64 bits signé dans le magasin SerializationInfo.Adds a 64-bit signed integer value into the SerializationInfo store.

AddValue(String, Object)

Ajoute l'objet spécifié dans le magasin SerializationInfo, où il est associé à un nom spécifié.Adds the specified object into the SerializationInfo store, where it is associated with a specified name.

AddValue(String, Object, Type)

Ajoute une valeur dans le magasin SerializationInfo, où value est associé à name et est sérialisé en tant que Typetype.Adds a value into the SerializationInfo store, where value is associated with name and is serialized as being of Typetype.

AddValue(String, SByte)

Ajoute une valeur entière 8 bits signée dans le magasin SerializationInfo.Adds an 8-bit signed integer value into the SerializationInfo store.

AddValue(String, Single)

Ajoute une valeur à virgule flottante simple précision dans le magasin SerializationInfo.Adds a single-precision floating-point value into the SerializationInfo store.

AddValue(String, UInt16)

Ajoute une valeur entière 16 bits non signée dans le magasin SerializationInfo.Adds a 16-bit unsigned integer value into the SerializationInfo store.

AddValue(String, UInt32)

Ajoute une valeur d’entier 32 bits non signé dans le magasin SerializationInfo.Adds a 32-bit unsigned integer value into the SerializationInfo store.

AddValue(String, UInt64)

Ajoute une valeur d’entier 64 bits non signé dans le magasin SerializationInfo.Adds a 64-bit unsigned integer value into the SerializationInfo store.

Equals(Object)

Détermine si l'objet spécifié est identique à l'objet actuel.Determines whether the specified object is equal to the current object.

(Hérité de Object)
GetBoolean(String)

Récupère une valeur booléenne du magasin SerializationInfo.Retrieves a Boolean value from the SerializationInfo store.

GetByte(String)

Récupère une valeur entière 8 bits non signée du magasin SerializationInfo.Retrieves an 8-bit unsigned integer value from the SerializationInfo store.

GetChar(String)

Récupère une valeur des caractères Unicode du magasin SerializationInfo.Retrieves a Unicode character value from the SerializationInfo store.

GetDateTime(String)

Récupère une valeur DateTime du magasin SerializationInfo.Retrieves a DateTime value from the SerializationInfo store.

GetDecimal(String)

Récupère une valeur décimale du magasin SerializationInfo.Retrieves a decimal value from the SerializationInfo store.

GetDouble(String)

Récupère une valeur à virgule flottante double précision du magasin SerializationInfo.Retrieves a double-precision floating-point value from the SerializationInfo store.

GetEnumerator()

Retourne SerializationInfoEnumerator utilisé pour itérer au sein des paires nom-valeur dans le magasin SerializationInfo.Returns a SerializationInfoEnumerator used to iterate through the name-value pairs in the SerializationInfo store.

GetHashCode()

Fait office de fonction de hachage par défaut.Serves as the default hash function.

(Hérité de Object)
GetInt16(String)

Récupère une valeur entière 16 bits signée du magasin SerializationInfo.Retrieves a 16-bit signed integer value from the SerializationInfo store.

GetInt32(String)

Récupère une valeur d’entier 32 bits signé du magasin SerializationInfo.Retrieves a 32-bit signed integer value from the SerializationInfo store.

GetInt64(String)

Récupère une valeur d’entier 64 bits signé du magasin SerializationInfo.Retrieves a 64-bit signed integer value from the SerializationInfo store.

GetSByte(String)

Récupère une valeur entière 8 bits signée du magasin SerializationInfo.Retrieves an 8-bit signed integer value from the SerializationInfo store.

GetSingle(String)

Récupère une valeur à virgule flottante simple précision du magasin SerializationInfo.Retrieves a single-precision floating-point value from the SerializationInfo store.

GetString(String)

Récupère une valeur String du magasin SerializationInfo.Retrieves a String value from the SerializationInfo store.

GetType()

Obtient le Type de l'instance actuelle.Gets the Type of the current instance.

(Hérité de Object)
GetUInt16(String)

Récupère une valeur entière 16 bits non signée du magasin SerializationInfo.Retrieves a 16-bit unsigned integer value from the SerializationInfo store.

GetUInt32(String)

Récupère une valeur d’entier 32 bits non signé du magasin SerializationInfo.Retrieves a 32-bit unsigned integer value from the SerializationInfo store.

GetUInt64(String)

Récupère une valeur d’entier 64 bits non signé du magasin SerializationInfo.Retrieves a 64-bit unsigned integer value from the SerializationInfo store.

GetValue(String, Type)

Récupère une valeur du magasin SerializationInfo.Retrieves a value from the SerializationInfo store.

MemberwiseClone()

Crée une copie superficielle de l'objet Object actuel.Creates a shallow copy of the current Object.

(Hérité de Object)
SetType(Type)

Définit Type de l'objet à sérialiser.Sets the Type of the object to serialize.

ToString()

Retourne une chaîne qui représente l'objet actuel.Returns a string that represents the current object.

(Hérité de Object)

S’applique à

Voir aussi