Classe DataMemberAttribute (System.Runtime.Serialization)

Cambia visualizzazione:
ScriptFree
Riferimento a .NET Framework
Classe DataMemberAttribute
Il presente articolo è stato tradotto manualmente. Per visualizzare questa pagina e contemporaneamente visualizzarne il contenuto in lingua inglese, passare alla visualizzazione semplificata.

Quando viene applicato al membro di un tipo, specifica che il membro fa parte di un contratto dati e può essere serializzato dalla classe DataContractSerializer.

Gerarchia di ereditarietà

System.Object
  System.Attribute
    System.Runtime.Serialization.DataMemberAttribute

Spazio dei nomi:  System.Runtime.Serialization
Assembly:  System.Runtime.Serialization (in System.Runtime.Serialization.dll)
Sintassi

Visual Basic
<AttributeUsageAttribute(AttributeTargets.Property Or AttributeTargets.Field, Inherited := False,  _
	AllowMultiple := False)> _
Public NotInheritable Class DataMemberAttribute _
	Inherits Attribute
C#
[AttributeUsageAttribute(AttributeTargets.Property|AttributeTargets.Field, Inherited = false, 
	AllowMultiple = false)]
public sealed class DataMemberAttribute : Attribute
Visual C++
[AttributeUsageAttribute(AttributeTargets::Property|AttributeTargets::Field, Inherited = false, 
	AllowMultiple = false)]
public ref class DataMemberAttribute sealed : public Attribute
F#
[<Sealed>]
[<AttributeUsageAttribute(AttributeTargets.Property|AttributeTargets.Field, Inherited = false, 
    AllowMultiple = false)>]
type DataMemberAttribute =  
    class
        inherit Attribute
    end

Il tipo DataMemberAttribute espone i seguenti membri.

Costruttori

  Nome Descrizione
Metodo pubblico ms574795.PortableClassLibrary(it-it,VS.100).gif DataMemberAttribute Inizializza una nuova istanza della classe DataMemberAttribute.
In alto
Proprietà

  Nome Descrizione
Proprietà pubblica ms574795.PortableClassLibrary(it-it,VS.100).gif EmitDefaultValue Ottiene o imposta un valore che specifica se serializzare il valore predefinito per un campo o proprietà da serializzare.
Proprietà pubblica ms574795.PortableClassLibrary(it-it,VS.100).gif IsRequired Ottiene o imposta un valore che indica al motore di serializzazione la necessità che il membro sia presente al momento della lettura o della deserializzazione.
Proprietà pubblica ms574795.PortableClassLibrary(it-it,VS.100).gif Name Ottiene o imposta il nome di un membro dati.
Proprietà pubblica ms574795.PortableClassLibrary(it-it,VS.100).gif Order Ottiene o imposta l'ordine di serializzazione e deserializzazione di un membro.
Proprietà pubblica TypeId Quando è implementata in una classe derivata, ottiene un identificatore univoco della classe Attribute. (Ereditato da Attribute)
In alto
Metodi

  Nome Descrizione
Metodo pubblico ms574795.PortableClassLibrary(it-it,VS.100).gif Equals Infrastruttura. Restituisce un valore che indica se l'istanza è uguale a un oggetto specificato. (Ereditato da Attribute)
Metodo protetto ms574795.PortableClassLibrary(it-it,VS.100).gif Finalize Consente a un oggetto di provare a liberare risorse ed eseguire altre operazioni di pulitura prima che l'oggetto stesso venga recuperato dalla procedura di Garbage Collection. (Ereditato da Object)
Metodo pubblico ms574795.PortableClassLibrary(it-it,VS.100).gif GetHashCode Restituisce il codice hash per l'istanza. (Ereditato da Attribute)
Metodo pubblico ms574795.PortableClassLibrary(it-it,VS.100).gif GetType Ottiene l'oggetto Type dell'istanza corrente. (Ereditato da Object)
Metodo pubblico IsDefaultAttribute Quando è sottoposto a override in una classe derivata, indica se il valore di questa istanza è il valore predefinito della classe derivata. (Ereditato da Attribute)
Metodo pubblico Match Quando è sottoposto a override in una classe derivata, restituisce un valore che indica se questa istanza equivale a un oggetto specificato. (Ereditato da Attribute)
Metodo protetto ms574795.PortableClassLibrary(it-it,VS.100).gif MemberwiseClone Consente di creare una copia dei riferimenti dell'oggetto Object corrente. (Ereditato da Object)
Metodo pubblico ms574795.PortableClassLibrary(it-it,VS.100).gif ToString Restituisce una stringa che rappresenta l'oggetto corrente. (Ereditato da Object)
In alto
Implementazioni esplicite dell'interfaccia

  Nome Descrizione
Implementazione esplicita dell'interfaccia Metodo privato _Attribute.GetIDsOfNames Esegue il mapping di un set di nomi a un set corrispondente di ID di invio. (Ereditato da Attribute)
Implementazione esplicita dell'interfaccia Metodo privato _Attribute.GetTypeInfo Recupera le informazioni sul tipo relative a un oggetto, che possono essere utilizzate per ottenere informazioni sul tipo relative a un'interfaccia. (Ereditato da Attribute)
Implementazione esplicita dell'interfaccia Metodo privato _Attribute.GetTypeInfoCount Recupera il numero delle interfacce di informazioni di tipo fornite da un oggetto (0 o 1). (Ereditato da Attribute)
Implementazione esplicita dell'interfaccia Metodo privato _Attribute.Invoke Fornisce l'accesso a proprietà e metodi esposti da un oggetto. (Ereditato da Attribute)
In alto
Note

Applicare l'attributo DataMemberAttribute insieme all'attributo DataContractAttribute per identificare membri di un tipo che fanno parte di un contratto dati. Uno dei serializzatori che possono serializzare contratti dati è DataContractSerializer.

Il modello del contratto dati è un modello di "consenso esplicito". L'applicazione di DataMemberAttribute a un campo o proprietà specifica in modo esplicito che il valore del membro verrà serializzato. Al contrario, BinaryFormatter serializza campi pubblici e privati di un tipo e XmlSerializer serializza soltanto campi e proprietà pubbliche di un tipo.

Nota di avviso Attenzione

È possibile applicare DataMemberAttribute a campi o proprietà private. Tenere presente che i dati restituiti dal membro (anche se privato) vengono serializzati e deserializzati e possono quindi essere visualizzati o intercettati da un utente o processo malintenzionato.

Per impostazione predefinita, il nome del membro CLR viene utilizzato come nome del membro dati. Se si imposta la proprietà Name è possibile personalizzare il nome del membro dati. Può essere utilizzato per fornire un nome che può non essere consentito come nome di membro CLR. Quando si esegue il mapping a XML utilizzando DataContractSerializer, questo nome viene utilizzato come nome dell'elemento dello schema in un tipo.

Nota Nota

Le proprietà alle quali è stato applicato l'attributo DataMemberAttribute devono disporre di entrambi i campi get e set. Non possono disporre solo del campo get o del campo set.

Per ulteriori informazioni sui contratti dati e sui membri dati, vedere Using Data Contracts. Per ulteriori informazioni sui nomi dei membri, vedere Data Member Default Values.

Esempi

Nell'esempio seguente vengono illustrati due tipi ai quali sono stati applicati gli attributi DataContractAttribute e DataMemberAttribute. La proprietà Name è impostata su "Customer".

Visual Basic

Imports System.Collections
Imports System.IO
Imports System.Runtime.Serialization
Imports System.Xml

' You must apply a DataContractAttribute or SerializableAttribute
' to a class to have it serialized by the DataContractSerializer.
<DataContract()>  _
Class Person
    Implements IExtensibleDataObject

    Private LastNameValue As String

    ' Apply the DataMemberAttribute to fields (or properties) 
    ' that must be serialized.

    <DataMember()>  _
    Public FirstName As String

    <DataMember()>  _
    Public Property LastName() As String
        Get
            Return LastNameValue 
        End Get

        Set(ByVal Value As String)
           LastNameValue = Value
        End Set
    End Property


    <DataMember(Name:="ID")>  _
    Public IdNumber As Integer

    ' Note that you can apply the DataMemberAttribute to 
    ' a private field as well.
    <DataMember()>  _
    Private Secret As String

    Public Sub New(ByVal newfName As String, ByVal newLName As String, ByVal newIdNumber As Integer) 
        FirstName = newfName
        LastName = newLName
        IdNumber = newIdNumber
        Secret = newfName + newLName + newIdNumber.ToString()

    End Sub 

    ' The ExtensionData field holds data from future versions 
    ' of the type.  This enables this type to be compatible with 
    ' future versions. The field is required to implement the 
    ' IExtensibleObjectData interface.
    Private extensionDataValue As ExtensionDataObject

    Public Property ExtensionData() As ExtensionDataObject _
       Implements IExtensibleDataObject.ExtensionData
        Get
            Return extensionDataValue
        End Get
        Set
            extensionDataValue = value
        End Set
    End Property
End Class 

Public Class Test
    Public Shared Sub Main(ByVal args() As String) 
        Try
            ReadObject("DataMemberAttributeExample.xml")
            WriteObject("DataMemberAttributeExample.xml")
        Catch exc As Exception
            Console.WriteLine("The serialization operation failed: {0} StackTrace: {1}", _
            exc.Message, exc.StackTrace)
        Finally
            Console.WriteLine("Press <Enter> to exit....")
            Console.ReadLine()
        End Try
    End Sub 

    Public Shared Sub ReadObject(ByVal filename As String) 
        ' Create a new instance of the Person class.
        Dim p1 As New Person("Zighetti", "Barbara", 101)
        Dim writer As New FileStream(filename, FileMode.Create)
        Dim ser As New DataContractSerializer(GetType(Person))
        ser.WriteObject(writer, p1)
        writer.Close()
    End Sub 

    Public Shared Sub WriteObject(ByVal filename As String) 
        ' Deserialize an instance of the Person class 
        ' from an XML file.
        Dim fs As New FileStream(filename, FileMode.OpenOrCreate)
        Dim ser As New DataContractSerializer(getTYpe(Person))
        ' Deserialize the data and read it from the instance.
        Dim deserializedPerson As Person = ser.ReadObject(fs)
        fs.Close()
        Console.WriteLine(String.Format("{0} {1}, ID: {2}", _
        deserializedPerson.FirstName, deserializedPerson.LastName, deserializedPerson.IdNumber))
    End Sub 
End Class 


C#

using System;
using System.Collections;
using System.IO;
using System.Runtime.Serialization;
using System.Xml;

// You must apply a DataContractAttribute or SerializableAttribute
// to a class to have it serialized by the DataContractSerializer.
[DataContract()]
class Person : IExtensibleDataObject
{
    private string LastNameValue;
    // Apply the DataMemberAttribute to fields (or properties) 
    // that must be serialized.
    [DataMember()]
    public string FirstName;

    [DataMember]
    public string LastName
    {
        get { return LastNameValue; }
        set { LastNameValue = value; }
    }

    [DataMember(Name = "ID")]
    public int IdNumber;

    // Note that you can apply the DataMemberAttribute to 
    // a private field as well.
    [DataMember]
    private string Secret;

    public Person(string newfName, string newLName, int newIdNumber)
    {
        FirstName = newfName;
        LastName = newLName;
        IdNumber = newIdNumber;
        Secret = newfName + newLName + newIdNumber;
    }

    // The extensionDataValue field holds data from future versions 
    // of the type.  This enables this type to be compatible with 
    // future versions. The field is required to implement the 
    // IExtensibleDataObject interface.

    private ExtensionDataObject extensionDatavalue;

    public ExtensionDataObject ExtensionData
    {
        get
        {
            return extensionDatavalue;
        }
        set
        {
            extensionDatavalue = value;
        }
    }
}

public class Test
{
    public static void Main(string[] args)
    {
        try
        {
            WriteObject(@"DataMemberAttributeExample.xml");
            ReadObject(@"DataMemberAttributeExample.xml");
        }
        catch (Exception exc)
        {
            Console.WriteLine(
            "The serialization operation failed: {0} StackTrace: {1}",
            exc.Message, exc.StackTrace);
        }
        finally
        {
            Console.WriteLine("Press <Enter> to exit....");
            Console.ReadLine();
        }
    }

    public static void WriteObject(string filename)
    {
        // Create a new instance of the Person class.
        Person p1 = new Person("Zighetti", "Barbara", 101);
        FileStream writer = new FileStream(filename,
        FileMode.OpenOrCreate);
        DataContractSerializer ser =
            new DataContractSerializer(typeof(Person));
        ser.WriteObject(writer, p1);
        writer.Close();
    }

    public static void ReadObject(string filename)
    {
        // Deserialize an instance of the Person class 
        // from an XML file.
        FileStream fs = new FileStream(filename,
        FileMode.OpenOrCreate);
        DataContractSerializer ser =
            new DataContractSerializer(typeof(Person));
        // Deserialize the data and read it from the instance.
        Person deserializedPerson = (Person)ser.ReadObject(fs);
        fs.Close();
        Console.WriteLine(String.Format("{0} {1}, ID: {2}",
        deserializedPerson.FirstName, deserializedPerson.LastName,
        deserializedPerson.IdNumber));
    }

}


Informazioni sulla versione

.NET Framework

Supportato in: 4, 3.5, 3.0

.NET Framework Client Profile

Supportato in: 4, 3.5 SP1

Supportato in:
Piattaforme

Windows 7, Windows Vista SP1 o versione successiva, Windows XP SP3, Windows Server 2008 (componenti di base del server non supportati), Windows Server 2008 R2 (componenti di base del server supportati con SP1 o versione successiva), Windows Server 2003 SP2

.NET Framework non supporta tutte le versioni di ciascuna piattaforma. Per un elenco delle versioni supportate, vedere Requisiti di sistema di .NET Framework.
Codice thread safe

Qualsiasi membro static (Shared in Visual Basic) pubblico di questo tipo è thread-safe. I membri di istanza non sono garantiti come thread-safe.
Vedere anche

Riferimenti