DataMemberAttribute クラス

定義

型のメンバーに適用する場合は、そのメンバーがデータ コントラクトの一部であり、DataContractSerializer によってシリアル化されることを指定します。

public ref class DataMemberAttribute sealed : Attribute
[System.AttributeUsage(System.AttributeTargets.Field | System.AttributeTargets.Property, AllowMultiple=false, Inherited=false)]
public sealed class DataMemberAttribute : Attribute
[<System.AttributeUsage(System.AttributeTargets.Field | System.AttributeTargets.Property, AllowMultiple=false, Inherited=false)>]
type DataMemberAttribute = class
    inherit Attribute
Public NotInheritable Class DataMemberAttribute
Inherits Attribute
継承
DataMemberAttribute
属性

次の例は、 属性と DataMemberAttribute 属性がDataContractAttribute適用されている型を示しています。 の DataMemberAttribute プロパティは Name "ID" に設定されています。

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));
    }
}
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

注釈

DataMemberAttribute 属性と DataContractAttribute を組み合わせて適用して、データ コントラクトの一部である型のメンバーを識別します。 データ コントラクトをシリアル化できるシリアライザーの 1 つに DataContractSerializer があります。

データ コントラクト モデルは、「opt-in」モデルです。 DataMemberAttribute のフィールドまたはプロパティへの適用は、メンバー値がシリアル化されることを明示的に指定します。 これに対し、 は XmlSerializer 型のすべてのパブリック フィールドとプロパティをシリアル化します。

注意事項

プライベートなフィールドまたはプロパティに DataMemberAttribute を適用できます。 メンバーから返されたデータ (プライベートであっても) はシリアル化および逆シリアル化されるため、悪意のあるユーザーまたはプロセスによって表示または傍受される可能性があることに注意してください。

既定では、CLR メンバー名がデータ メンバーの名前として使用されます。 Name プロパティを設定することで、データ メンバーの名前をカスタマイズできます。 これにより、CLR メンバー名としては許可されない名前を用意できます。 DataContractSerializer を使用して XML にマッピングするとき、この名前が、型のスキーマ要素の名前として使用されます。

注意

属性がDataMemberAttribute適用されているプロパティには、 と set の両方getのフィールドが必要です。 -only または set-only にgetすることはできません。 デザインによってのみ残 getす必要があるプロパティ (コレクションを返すプロパティなど) をシリアル化するには、代わりに バッキング フィールドに を適用 DataMemberAttribute することを検討してください。

データ コントラクトとデータ メンバーの詳細については、「データ コントラクトの使用」を参照してください。 メンバー名の詳細については、「 データ メンバーの既定値」を参照してください。

コンストラクター

DataMemberAttribute()

DataMemberAttribute クラスの新しいインスタンスを初期化します。

プロパティ

EmitDefaultValue

シリアル化されるフィールドまたはプロパティのデフォルト値をシリアル化するかどうかを指定する値を取得または設定します。

IsNameSetExplicitly

Name が明示的に設定されているかどうかを取得します。

IsRequired

読み取りまたは逆シリアル化を行うときにメンバーが存在しなければならないシリアル化エンジンを指示する値を取得または設定します。

Name

データ メンバー名を取得または設定します。

Order

メンバーのシリアル化と逆シリアル化の順序を取得または設定します。

TypeId

派生クラスで実装されると、この Attribute の一意の識別子を取得します。

(継承元 Attribute)

メソッド

Equals(Object)

このインスタンスが、指定されたオブジェクトと等価であるかどうかを示す値を返します。

(継承元 Attribute)
GetHashCode()

このインスタンスのハッシュ コードを返します。

(継承元 Attribute)
GetType()

現在のインスタンスの Type を取得します。

(継承元 Object)
IsDefaultAttribute()

派生クラスでオーバーライドされるとき、このインスタンスの値が派生クラスの既定値であるかどうかを示します。

(継承元 Attribute)
Match(Object)

派生クラス内でオーバーライドされたときに、指定したオブジェクトとこのインスタンスが等しいかどうかを示す値を返します。

(継承元 Attribute)
MemberwiseClone()

現在の Object の簡易コピーを作成します。

(継承元 Object)
ToString()

現在のオブジェクトを表す文字列を返します。

(継承元 Object)

明示的なインターフェイスの実装

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

一連の名前を対応する一連のディスパッチ識別子に割り当てます。

(継承元 Attribute)
_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

オブジェクトの型情報を取得します。この情報はインターフェイスの型情報の取得に使用できます。

(継承元 Attribute)
_Attribute.GetTypeInfoCount(UInt32)

オブジェクトが提供する型情報インターフェイスの数 (0 または 1) を取得します。

(継承元 Attribute)
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

オブジェクトによって公開されたプロパティおよびメソッドへのアクセスを提供します。

(継承元 Attribute)

適用対象

こちらもご覧ください