DataContractAttribute 클래스

정의

형식이 데이터 계약을 정의하거나 구현하며, DataContractSerializer와 같은 serializer를 통해 serialize할 수 있도록 지정합니다. 형식을 serialize할 수 있게 만들려면 형식 작성자가 형식에 대해 데이터 계약을 정의해야 합니다.

public ref class DataContractAttribute sealed : Attribute
[System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Enum | System.AttributeTargets.Struct, AllowMultiple=false, Inherited=false)]
public sealed class DataContractAttribute : Attribute
[<System.AttributeUsage(System.AttributeTargets.Class | System.AttributeTargets.Enum | System.AttributeTargets.Struct, AllowMultiple=false, Inherited=false)>]
type DataContractAttribute = class
    inherit Attribute
Public NotInheritable Class DataContractAttribute
Inherits Attribute
상속
DataContractAttribute
특성

예제

다음 예에서는 가 적용된 라는 PersonDataContractAttribute 클래스를 직렬화하고 역직렬화합니다. NamespaceName 속성은 기본 설정을 재정의하는 값으로 설정되었습니다.

namespace DataContractAttributeExample
{
    // Set the Name and Namespace properties to new values.
    [DataContract(Name = "Customer", Namespace = "http://www.contoso.com")]
    class Person : IExtensibleDataObject
    {
        // To implement the IExtensibleDataObject interface, you must also
        // implement the ExtensionData property.
        private ExtensionDataObject extensionDataObjectValue;
        public ExtensionDataObject ExtensionData
        {
            get
            {
                return extensionDataObjectValue;
            }
            set
            {
                extensionDataObjectValue = value;
            }
        }

        [DataMember(Name = "CustName")]
        internal string Name;

        [DataMember(Name = "CustID")]
        internal int ID;

        public Person(string newName, int newID)
        {
            Name = newName;
            ID = newID;
        }
    }

    class Test
    {
        public static void Main()
        {
            try
            {
                WriteObject("DataContractExample.xml");
                ReadObject("DataContractExample.xml");
                Console.WriteLine("Press Enter to end");
                Console.ReadLine();
            }
            catch (SerializationException se)
            {
                Console.WriteLine
                ("The serialization operation failed. Reason: {0}",
                  se.Message);
                Console.WriteLine(se.Data);
                Console.ReadLine();
            }
        }

        public static void WriteObject(string path)
        {
            // Create a new instance of the Person class and
            // serialize it to an XML file.
            Person p1 = new Person("Mary", 1);
            // Create a new instance of a StreamWriter
            // to read and write the data.
            FileStream fs = new FileStream(path,
            FileMode.Create);
            XmlDictionaryWriter writer = XmlDictionaryWriter.CreateTextWriter(fs);
            DataContractSerializer ser =
                new DataContractSerializer(typeof(Person));
            ser.WriteObject(writer, p1);
            Console.WriteLine("Finished writing object.");
            writer.Close();
            fs.Close();
        }
        public static void ReadObject(string path)
        {
            // Deserialize an instance of the Person class
            // from an XML file. First create an instance of the
            // XmlDictionaryReader.
            FileStream fs = new FileStream(path, FileMode.OpenOrCreate);
            XmlDictionaryReader reader =
                XmlDictionaryReader.CreateTextReader(fs, new XmlDictionaryReaderQuotas());

            // Create the DataContractSerializer instance.
            DataContractSerializer ser =
                new DataContractSerializer(typeof(Person));

            // Deserialize the data and read it from the instance.
            Person newPerson = (Person)ser.ReadObject(reader);
            Console.WriteLine("Reading this object:");
            Console.WriteLine(String.Format("{0}, ID: {1}",
            newPerson.Name, newPerson.ID));
            fs.Close();
        }
    }
}
Namespace DataContractAttributeExample
    ' Set the Name and Namespace properties to new values.
    <DataContract(Name := "Customer", [Namespace] := "http://www.contoso.com")>  _
    Class Person
        Implements IExtensibleDataObject
        ' To implement the IExtensibleDataObject interface, you must also
        ' implement the ExtensionData property.
        Private extensionDataObjectValue As ExtensionDataObject 
        
        Public Property ExtensionData() As ExtensionDataObject _
          Implements IExtensibleDataObject.ExtensionData
            Get
                Return extensionDataObjectValue
            End Get
            Set
                extensionDataObjectValue = value
            End Set
        End Property
        
        <DataMember(Name := "CustName")>  _
        Friend Name As String
        
        <DataMember(Name := "CustID")>  _
        Friend ID As Integer
        
        
        Public Sub New(ByVal newName As String, ByVal newID As Integer) 
            Name = newName
            ID = newID
        
        End Sub 
    End Class 
    
    
    Class Test
        
        Public Shared Sub Main() 
            Try
                WriteObject("DataContractExample.xml")
                ReadObject("DataContractExample.xml")
                Console.WriteLine("Press Enter to end")
                Console.ReadLine()
            Catch se As SerializationException
                Console.WriteLine("The serialization operation failed. Reason: {0}", _
                   se.Message)
                Console.WriteLine(se.Data)
                Console.ReadLine()
            End Try
        
        End Sub 
        
        
        Public Shared Sub WriteObject(ByVal path As String) 
            ' Create a new instance of the Person class and 
            ' serialize it to an XML file.
            Dim p1 As New Person("Mary", 1)
            ' Create a new instance of a StreamWriter
            ' to read and write the data.
            Dim fs As New FileStream(path, FileMode.Create)
            Dim writer As XmlDictionaryWriter = XmlDictionaryWriter.CreateTextWriter(fs)
            Dim ser As New DataContractSerializer(GetType(Person))
            ser.WriteObject(writer, p1)
            Console.WriteLine("Finished writing object.")
            writer.Close()
            fs.Close()
        
        End Sub 
        
        Public Shared Sub ReadObject(ByVal path As String) 
            ' Deserialize an instance of the Person class 
            ' from an XML file. First create an instance of the 
            ' XmlDictionaryReader.
            Dim fs As New FileStream(path, FileMode.OpenOrCreate)
            Dim reader As XmlDictionaryReader = XmlDictionaryReader. _
              CreateTextReader(fs, New XmlDictionaryReaderQuotas())
            
            ' Create the DataContractSerializer instance.
            Dim ser As New DataContractSerializer(GetType(Person))
            
            ' Deserialize the data and read it from the instance.
            Dim newPerson As Person = CType(ser.ReadObject(reader), Person)
            Console.WriteLine("Reading this object:")
            Console.WriteLine(String.Format("{0}, ID: {1}", newPerson.Name, newPerson.ID))
            fs.Close()
        
        End Sub 
    End Class 
End Namespace

설명

이 API에 대한 자세한 내용은 DataContractAttribute에 대한 추가 API 설명을 참조하세요.

생성자

DataContractAttribute()

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

속성

IsNameSetExplicitly

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

IsNamespaceSetExplicitly

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

IsReference

개체 참조 데이터를 유지할지 여부를 나타내는 값을 가져오거나 설정합니다.

IsReferenceSetExplicitly

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

Name

형식의 데이터 계약 이름을 가져오거나 설정합니다.

Namespace

형식에 대한 데이터 계약의 네임스페이스를 가져오거나 설정합니다.

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)

적용 대상

추가 정보