SerializableAttribute SerializableAttribute SerializableAttribute SerializableAttribute Class

Définition

Indique qu'une classe peut être sérialisée.Indicates that a class can be serialized. Cette classe ne peut pas être héritée.This class cannot be inherited.

public ref class SerializableAttribute sealed : Attribute
[System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Struct | System.AttributeTargets.Enum | System.AttributeTargets.Delegate, Inherited=false)]
[System.Runtime.InteropServices.ComVisible(true)]
[System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Delegate | System.AttributeTargets.Enum | System.AttributeTargets.Struct, Inherited=false)]
public sealed class SerializableAttribute : Attribute
type SerializableAttribute = class
    inherit Attribute
Public NotInheritable Class SerializableAttribute
Inherits Attribute
Héritage
SerializableAttributeSerializableAttributeSerializableAttributeSerializableAttribute
Attributs

Exemples

L’exemple suivant illustre la sérialisation d’un objet qui est marqué avec le SerializableAttribute attribut.The following example demonstrates serialization of an object that is marked with the SerializableAttribute attribute. Pour utiliser le BinaryFormatter au lieu du SoapFormatter, ne pas commenter les lignes appropriées.To use the BinaryFormatter instead of the SoapFormatter, uncomment the appropriate lines.

#using <system.dll>
#using <system.messaging.dll>
#using <System.Runtime.Serialization.Formatters.Soap.dll>

using namespace System;
using namespace System::IO;
using namespace System::Runtime::Serialization::Formatters::Soap;

// A test object that needs to be serialized.

[Serializable]
ref class TestSimpleObject
{
private:
   int member1;
   String^ member2;
   String^ member3;
   double member4;

public:

   // A field that is not serialized.

   [NonSerialized]
   String^ member5;
   TestSimpleObject()
   {
      member1 = 11;
      member2 = "hello";
      member3 = "hello";
      member4 = 3.14159265;
      member5 = "hello world!";
   }

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

};

int main()
{
   
   //Creates a new TestSimpleObject object.
   TestSimpleObject^ obj = gcnew TestSimpleObject;
   Console::WriteLine( "Before serialization the Object* contains: " );
   obj->Print();
   
   //Opens a file and serializes the object into it in binary format.
   Stream^ stream = File::Open( "data.xml", FileMode::Create );
   SoapFormatter^ formatter = gcnew SoapFormatter;
   
   //BinaryFormatter* formatter = new BinaryFormatter();
   formatter->Serialize( stream, obj );
   stream->Close();
   
   //Empties obj.
   obj = nullptr;
   
   //Opens file S"data.xml" and deserializes the object from it.
   stream = File::Open( "data.xml", FileMode::Open );
   formatter = gcnew SoapFormatter;
   
   //formatter = new BinaryFormatter();
   obj = dynamic_cast<TestSimpleObject^>(formatter->Deserialize( stream ));
   stream->Close();
   Console::WriteLine( "" );
   Console::WriteLine( "After deserialization the object contains: " );
   obj->Print();
}

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

public class Test {
   public static void Main()  {

      //Creates a new TestSimpleObject object.
      TestSimpleObject obj = new TestSimpleObject();

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

      //Opens a file and serializes the object into it in binary format.
      Stream stream = File.Open("data.xml", FileMode.Create);
      SoapFormatter formatter = new SoapFormatter();

      //BinaryFormatter formatter = new BinaryFormatter();

      formatter.Serialize(stream, obj);
      stream.Close();
   
      //Empties obj.
      obj = null;
   
      //Opens file "data.xml" and deserializes the object from it.
      stream = File.Open("data.xml", FileMode.Open);
      formatter = new SoapFormatter();

      //formatter = new BinaryFormatter();

      obj = (TestSimpleObject)formatter.Deserialize(stream);
      stream.Close();

      Console.WriteLine("");
      Console.WriteLine("After deserialization the object contains: ");
      obj.Print();
   }
}


// A test object that needs to be serialized.
[Serializable()]		
public class TestSimpleObject  {

    public int member1;
    public string member2;
    public string member3;
    public double member4;
    
    // A field that is not serialized.
    [NonSerialized()] public string member5; 
    
    public TestSimpleObject() {

        member1 = 11;
        member2 = "hello";
        member3 = "hello";
        member4 = 3.14159265;
        member5 = "hello world!";
    }


    public void Print() {

        Console.WriteLine("member1 = '{0}'", member1);
        Console.WriteLine("member2 = '{0}'", member2);
        Console.WriteLine("member3 = '{0}'", member3);
        Console.WriteLine("member4 = '{0}'", member4);
        Console.WriteLine("member5 = '{0}'", member5);
    }
}
Imports System
Imports System.IO
Imports System.Runtime.Serialization
Imports System.Runtime.Serialization.Formatters.Soap




Public Class Test
   
   Public Shared Sub Main()
      
      ' Creates a new TestSimpleObject object.
      Dim obj As New TestSimpleObject()
      
      Console.WriteLine("Before serialization the object contains: ")
      obj.Print()
      
      ' Opens a file and serializes the object into it in binary format.
      Dim stream As Stream = File.Open("data.xml", FileMode.Create)
      Dim formatter As New SoapFormatter()
      


      formatter.Serialize(stream, obj)
      stream.Close()
      
      ' Empties obj.
      obj = Nothing
      
      ' Opens file "data.xml" and deserializes the object from it.
      stream = File.Open("data.xml", FileMode.Open)
      formatter = New SoapFormatter()



      obj = CType(formatter.Deserialize(stream), TestSimpleObject)
      stream.Close()
      
      Console.WriteLine("")
      Console.WriteLine("After deserialization the object contains: ")
      obj.Print()

   End Sub 'Main

End Class 'Test


' A test object that needs to be serialized.
<Serializable()> Public Class TestSimpleObject
   
   Public member1 As Integer
   Public member2 As String
   Public member3 As String
   Public member4 As Double
   
   ' A member that is not serialized.
   <NonSerialized()> Public member5 As String  
  
   
   Public Sub New()     
      member1 = 11
      member2 = "hello"
      member3 = "hello"
      member4 = 3.14159265
      member5 = "hello world!"
   End Sub 'New
      
   
   Public Sub Print()      
      Console.WriteLine("member1 = '{0}'", member1)
      Console.WriteLine("member2 = '{0}'", member2)
      Console.WriteLine("member3 = '{0}'", member3)
      Console.WriteLine("member4 = '{0}'", member4)
      Console.WriteLine("member5 = '{0}'", member5)
   End Sub 'Print

End Class 'TestSimpleObject

Remarques

Appliquez l’attribut SerializableAttribute à un type pour indiquer que les instances de ce type peuvent être sérialisées.Apply the SerializableAttribute attribute to a type to indicate that instances of this type can be serialized. Le common language runtime lève SerializationException si n’importe quel type dans le graphique d’objets en cours de sérialisation n’a pas la SerializableAttribute attribut appliqué.The common language runtime throws SerializationException if any type in the graph of objects being serialized does not have the SerializableAttribute attribute applied.

Appliquer le SerializableAttribute attribut même si la classe implémente également le ISerializable interface pour contrôler le processus de sérialisation.Apply the SerializableAttribute attribute even if the class also implements the ISerializable interface to control the serialization process.

Lorsque vous appliquez le SerializableAttribute attribut à un type, tous les champs privés et publics sont sérialisés par défaut.When you apply the SerializableAttribute attribute to a type, all private and public fields are serialized by default. Vous pouvez contrôler sérialisation plus granulaire en implémentant le ISerializable interface pour remplacer le processus de sérialisation.You can control serialization more granularly by implementing the ISerializable interface to override the serialization process.

Ou vous pouvez exclure des champs de la sérialisation en appliquant la NonSerializedAttribute au champ d’attribut.Or you can exclude fields from serialization by applying the NonSerializedAttribute attribute to the field. Si un champ d’un type sérialisable contient un pointeur, un handle ou une autre structure de données qui est spécifique à un environnement particulier et ne peut pas être reconstitué de manière significative dans un autre environnement, vous pouvez souhaiter appliquer le NonSerializedAttribute attribut à ce champ.If a field of a serializable type contains a pointer, a handle, or some other data structure that is specific to a particular environment, and cannot be meaningfully reconstituted in a different environment, then you might want to apply the NonSerializedAttribute attribute to that field.

Pour plus d’informations sur l’utilisation d’attributs, consultez attributs.For more information about using attributes, see Attributes. Pour plus d'informations sur la sérialisation, consultez System.Runtime.Serialization.For more information about serialization, see System.Runtime.Serialization.

Constructeurs

SerializableAttribute() SerializableAttribute() SerializableAttribute() SerializableAttribute()

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

Méthodes

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

Retourne une valeur qui indique si cette instance est égale à un objet spécifié.Returns a value that indicates whether this instance is equal to a specified object.

(Inherited from Attribute)
GetHashCode() GetHashCode() GetHashCode() GetHashCode()

Retourne le code de hachage de cette instance.Returns the hash code for this instance.

(Inherited from Attribute)
GetType() GetType() GetType() GetType()

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

(Inherited from Object)
IsDefaultAttribute() IsDefaultAttribute() IsDefaultAttribute() IsDefaultAttribute()

En cas de substitution dans une classe dérivée, indique si la valeur de cette instance est la valeur par défaut pour la classe dérivée.When overridden in a derived class, indicates whether the value of this instance is the default value for the derived class.

(Inherited from Attribute)
Match(Object) Match(Object) Match(Object) Match(Object)

En cas de substitution dans une classe dérivée, retourne une valeur indiquant si cette instance équivaut à un objet spécifié.When overridden in a derived class, returns a value that indicates whether this instance equals a specified object.

(Inherited from Attribute)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

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

(Inherited from Object)
ToString() ToString() ToString() ToString()

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

(Inherited from Object)

Implémentations d’interfaces explicites

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

Mappe un jeu de noms avec un jeu correspondant d'identificateurs de dispatch.Maps a set of names to a corresponding set of dispatch identifiers.

(Inherited from Attribute)
_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr) _Attribute.GetTypeInfo(UInt32, UInt32, IntPtr) _Attribute.GetTypeInfo(UInt32, UInt32, IntPtr) _Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

Récupère les informations de type pour un objet, qui peuvent être utilisées pour obtenir les informations de type d'une interface.Retrieves the type information for an object, which can be used to get the type information for an interface.

(Inherited from Attribute)
_Attribute.GetTypeInfoCount(UInt32) _Attribute.GetTypeInfoCount(UInt32) _Attribute.GetTypeInfoCount(UInt32) _Attribute.GetTypeInfoCount(UInt32)

Récupère le nombre d'interfaces d'informations de type fourni par un objet (0 ou 1).Retrieves the number of type information interfaces that an object provides (either 0 or 1).

(Inherited from Attribute)
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) _Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) _Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) _Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

Fournit l'accès aux propriétés et aux méthodes exposées par un objet.Provides access to properties and methods exposed by an object.

(Inherited from Attribute)

Propriétés

TypeId TypeId TypeId TypeId

Lors de l'implémentation dans une classe dérivée, obtient un identificateur unique pour l'objet Attribute.When implemented in a derived class, gets a unique identifier for this Attribute.

(Inherited from Attribute)

S’applique à

Voir aussi