DataMemberAttribute 클래스

정의

형식의 멤버에 적용될 때 멤버가 데이터 계약의 일부이며 DataContractSerializer를 통해 serialize할 수 있음을 지정합니다.

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 특성을 적용하여 데이터 계약의 일부인 형식의 멤버를 식별합니다. 데이터 계약을 직렬화할 수 있는 직렬 변환기 중 하나는 입니다 DataContractSerializer.

데이터 계약 모델은 "옵트인" 모델입니다. 필드 또는 속성에 를 DataMemberAttribute 적용하면 멤버 값이 직렬화되도록 명시적으로 지정됩니다. 반면, 는 XmlSerializer 형식의 모든 공용 필드와 속성을 직렬화합니다.

주의

프라이빗 필드 또는 속성에 를 DataMemberAttribute 적용할 수 있습니다. 멤버가 반환한 데이터(프라이빗인 경우에도)는 직렬화 및 역직렬화되므로 악의적인 사용자 또는 프로세스에서 보거나 가로챌 수 있습니다.

기본적으로 CLR 멤버 이름은 데이터 멤버의 이름으로 사용됩니다. 속성을 설정 Name 하여 데이터 멤버의 이름을 사용자 지정할 수 있습니다. CLR 멤버 이름으로 허용되지 않을 수 있는 이름을 제공하는 데 사용할 수 있습니다. 를 사용하여 XML에 DataContractSerializer매핑할 때 이 이름은 형식의 스키마 요소 이름으로 사용됩니다.

참고

특성이 DataMemberAttribute 적용된 속성에는 및 set 필드가 모두 get 있어야 합니다. -only 또는 set-only일 get수 없습니다. 디자인에 의해서만 유지 get되어야 하는 속성(예: 컬렉션을 반환하는 속성)을 직렬화하려면 대신 를 지원 필드에 적용하는 DataMemberAttribute 것이 좋습니다.

데이터 계약 및 데이터 멤버에 대한 자세한 내용은 데이터 계약 사용을 참조하세요. 멤버 이름에 대한 자세한 내용은 데이터 멤버 기본값을 참조하세요.

생성자

DataMemberAttribute()

DataMemberAttribute 클래스의 새 인스턴스를 초기화합니다.

속성

EmitDefaultValue

serialize할 필드나 속성에 대한 기본값을 serialize하는지 여부를 지정하는 값을 가져오거나 설정합니다.

IsNameSetExplicitly

Name이 명시적으로 설정되었는지를 나타내는 값을 가져옵니다.

IsRequired

읽거나 역직렬화할 때 멤버가 있어야 함을 serialization 엔진에 알려 주는 값을 가져오거나 설정합니다.

Name

데이터 멤버 이름을 가져오거나 설정합니다.

Order

멤버의 serialization 및 deserialization 순서를 가져오거나 설정합니다.

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)

적용 대상

추가 정보