DataContractAttribute 類別

定義

指定定義或實作資料合約的型別,可由序列化程式 (例如 DataContractSerializer) 加以序列化。Specifies that the type defines or implements a data contract and is serializable by a serializer, such as the DataContractSerializer. 型別作者一定要定義型別的資料合約,才能讓型別能夠進行序列化。To make their type serializable, type authors must define a data contract for their type.

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
type DataContractAttribute = class
    inherit Attribute
Public NotInheritable Class DataContractAttribute
Inherits Attribute
繼承
DataContractAttribute
屬性

範例

下列範例會序列化和還原序列化名稱為 Person 且已套用 DataContractAttribute 的類別。The following example serializes and deserializes a class named Person to which the DataContractAttribute has been applied. 請注意,NamespaceName 屬性的值已經設定為將覆寫預設設定。Note that the Namespace and Name properties have been set to values that override the default settings.

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 

備註

DataContractAttribute 屬性套用至 DataContractSerializer 在序列化 (Serialization) 和還原序列化 (Deserialization) 作業中所使用的型別 (類別、結構或列舉)。Apply the DataContractAttribute attribute to types (classes, structures, or enumerations) that are used in serialization and deserialization operations by the DataContractSerializer. 如果您使用 Windows Communication Foundation (WCF)基礎結構來傳送或接收訊息,您也應該將DataContractAttribute套用至任何保存和操作訊息中所傳送之資料的類別。If you send or receive messages by using the Windows Communication Foundation (WCF) infrastructure, you should also apply the DataContractAttribute to any classes that hold and manipulate data sent in messages. 如需資料合約的詳細資訊,請參閱使用資料合約For more information about data contracts, see Using Data Contracts.

您也必須將 DataMemberAttribute 套用至負責保存您要序列化之值的任何欄位、屬性或事件。You must also apply the DataMemberAttribute to any field, property, or event that holds values you want to serialize. 透過套用 DataContractAttribute,您便可以明確地讓 DataContractSerializer 能夠序列化和還原序列化資料。By applying the DataContractAttribute, you explicitly enable the DataContractSerializer to serialize and deserialize the data.

警告

您可以將 DataMemberAttribute 套用至私用欄位。You can apply the DataMemberAttribute to private fields. 請注意,此欄位 (即使它是私用欄位) 傳回的資料會進行序列化和還原序列化,因此可能會遭到惡意使用者或處理序的檢視或攔截。Be aware that the data returned by the field (even if it is private) is serialized and deserialized, and thus can be viewed or intercepted by a malicious user or process.

如需資料合約的詳細資訊,請參閱使用資料合約中列出的主題。For more information about data contracts, see the topics listed in Using Data Contracts.

資料合約Data Contracts

資料合約」(data contract )是一組欄位的摘要描述,每個欄位都有名稱和資料類型。A data contract is an abstract description of a set of fields with a name and data type for each field. 資料合約存在於任何單一實作之外,以便讓不同平台上的服務能夠相互操作。The data contract exists outside of any single implementation to allow services on different platforms to interoperate. 只要在服務之間傳遞的資料符合相同的合約,所有服務就能夠處理該份資料。As long as the data passed between the services conforms to the same contract, all the services can process the data. 這種處理也稱為鬆散耦合系統This processing is also known as a loosely coupled system. 資料合約也類似一種介面,而在這種介面中,合約會指定資料必須如何傳遞才可讓應用程式加以處理。A data contract is also similar to an interface in that the contract specifies how data must be delivered so that it can be processed by an application. 例如,資料合約可能會要求名為 "Person" 並包含兩個名稱分別為 "FirstName" 和 "LastName" 之文字欄位的資料型別。For example, the data contract may call for a data type named "Person" that has two text fields, named "FirstName" and "LastName". 若要建立資料合約,請將 DataContractAttribute 套用至類別,並將 DataMemberAttribute 套用至必須進行序列化的任何欄位或屬性。To create a data contract, apply the DataContractAttribute to the class and apply the DataMemberAttribute to any fields or properties that must be serialized. 當完成序列化之後,資料就會符合已在該型別中隱含內建的資料合約。When serialized, the data conforms to the data contract that is implicitly built into the type.

注意

就繼承行為來看,資料合約與實際的介面有很大的不同。A data contract differs significantly from an actual interface in its inheritance behavior. 介面是繼承自任何衍生的型別。Interfaces are inherited by any derived types. 當您將 DataContractAttribute 套用至基底類別時,衍生的型別並不會繼承屬性或行為。When you apply the DataContractAttribute to a base class, the derived types do not inherit the attribute or the behavior. 但是,如果衍生的型別擁有資料合約,該基底類別的資料成員就會進行序列化。However, if a derived type has a data contract, the data members of the base class are serialized. 但是您必須將 DataMemberAttribute 套用至衍生類別的新成員,才能讓這些成員進行序列化。However, you must apply the DataMemberAttribute to new members in a derived class to make them serializable.

XML 結構描述文件和 SvcUtil 工具XML Schema Documents and the SvcUtil Tool

如果您要與其他服務交換資料,就必須描述資料合約。If you are exchanging data with other services, you must describe the data contract. 若是最新版本的 DataContractSerializer,則可以使用 XML 結構描述來定義資料合約For the current version of the DataContractSerializer, an XML schema can be used to define data contracts. (可以使用其他的中繼資料/描述形式來達成相同目的)。若要從您的應用程式建立 XML 架構,請使用System.servicemodel 中繼資料公用程式工具(Svcutil)搭配 /dconly命令列選項。(Other forms of metadata/description could be used for the same purpose.) To create an XML schema from your application, use the ServiceModel Metadata Utility Tool (Svcutil.exe) with the /dconly command line option. 根據預設,如果工具的輸入項目是組件時,工具就會產生 XML 結構描述集合,而此集合會定義在該組件中找到的所有資料合約型別。When the input to the tool is an assembly, by default, the tool generates a set of XML schemas that define all the data contract types found in that assembly. 相反地,您也可以使用 Svcutil.exe 工具來建立符合 XML 結構描述需求的 Visual Basic 或 C# 類別定義,而這些結構描述會使用能夠透過資料合約表示的建構。Conversely, you can also use the Svcutil.exe tool to create Visual Basic or C# class definitions that conform to the requirements of XML schemas that use constructs that can be expressed by data contracts. 在此情況下,不需要 /dconly命令列選項。In this case, the /dconly command line option is not required.

根據預設,如果 Svcutil.exe 工具的輸入項目是 XML 結構描述,工具就會建立類別集合。If the input to the Svcutil.exe tool is an XML schema, by default, the tool creates a set of classes. 如果您檢查這些類別,您就會發現此時已套用了 DataContractAttributeIf you examine those classes, you find that the DataContractAttribute has been applied. 您可以使用這些類別來建立新的應用程式,以便處理必須與其他服務交換的資料。You can use those classes to create a new application to process data that must be exchanged with other services.

您也可以針對傳回 Web 服務描述語言(WSDL)檔的端點執行此工具,以自動產生程式碼和設定來建立 Windows Communication Foundation (WCF)用戶端。You can also run the tool against an endpoint that returns a Web Services Description Language (WSDL) document to automatically generate the code and configuration to create an Windows Communication Foundation (WCF) client. 所產生的程式碼會包含以 DataContractAttribute 標記的型別。The generated code includes types that are marked with the DataContractAttribute.

重複使用現有的型別Reusing Existing Types

資料合約有兩項基本要求,一個是穩定的名稱,另一個則是成員的清單。A data contract has two basic requirements: a stable name and a list of members. 穩定的名稱是由命名空間統一資源識別元 (URI) 以及合約的本機名稱組成。The stable name consists of the namespace uniform resource identifier (URI) and the local name of the contract. 根據預設,當您將DataContractAttribute套用至類別時,它會使用類別名稱做為「區功能變數名稱稱」和類別的命名空間( "http://schemas.datacontract.org/2004/07/"前面加上)做為命名空間 URI。By default, when you apply the DataContractAttribute to a class, it uses the class name as the local name and the class's namespace (prefixed with "http://schemas.datacontract.org/2004/07/") as the namespace URI. 您可以藉由設定 NameNamespace 屬性來覆寫預設值。You can override the defaults by setting the Name and Namespace properties. 您也可以藉由將 ContractNamespaceAttribute 套用至命名空間以變更命名空間。You can also change the namespace by applying the ContractNamespaceAttribute to the namespace. 當現有的型別能夠完全依照需求處理資料,但卻擁有與資料合約不同的命名空間和類別名稱時,您就可以使用這項功能。Use this capability when you have an existing type that processes data exactly as you require but has a different namespace and class name from the data contract. 藉由覆寫預設值,您就可以重複使用現有的型別,並使已序列化的資料符合資料合約。By overriding the default values, you can reuse your existing type and have the serialized data conform to the data contract.

注意

您可以在任何程式碼中使用 DataContract 一字來代替較長的 DataContractAttributeIn any code, you can use the word DataContract instead of the longer DataContractAttribute.

版本控制Versioning

資料合約也能配合本身的較新版本。A data contract can also accommodate later versions of itself. 也就是說,當合約的較新版本含有其他資料時,這時會儲存該份資料,然後將其原封不動地傳回給傳送者。That is, when a later version of the contract includes extra data, that data is stored and returned to a sender untouched. 若要執行這個步驟,請實作 IExtensibleDataObject 介面。To do this, implement the IExtensibleDataObject interface.

如需版本控制的詳細資訊,請參閱資料合約版本控制For more information about versioning, see Data Contract Versioning.

建構函式

DataContractAttribute()

初始化 DataContractAttribute 類別的新執行個體。Initializes a new instance of the DataContractAttribute class.

屬性

IsNameSetExplicitly

取得是否已明確設定 NameGets whether Name has been explicitly set.

IsNamespaceSetExplicitly

取得是否已明確設定 NamespaceGets whether Namespace has been explicitly set.

IsReference

取得或設定值,這個值表示是否要保留物件參考資料。Gets or sets a value that indicates whether to preserve object reference data.

IsReferenceSetExplicitly

取得是否已明確設定 IsReferenceGets whether IsReference has been explicitly set.

Name

取得或設定型別的資料合約名稱。Gets or sets the name of the data contract for the type.

Namespace

取得或設定型別之資料合約的命名空間。Gets or sets the namespace for the data contract for the type.

TypeId

在衍生類別中實作時,取得這個 Attribute 的唯一識別碼。When implemented in a derived class, gets a unique identifier for this Attribute.

(繼承來源 Attribute)

方法

Equals(Object)

傳回值,這個值指出此執行個體是否與指定的物件相等。Returns a value that indicates whether this instance is equal to a specified object.

(繼承來源 Attribute)
GetHashCode()

傳回這個執行個體的雜湊碼。Returns the hash code for this instance.

(繼承來源 Attribute)
GetType()

取得目前執行個體的 TypeGets the Type of the current instance.

(繼承來源 Object)
IsDefaultAttribute()

在衍生類別中覆寫時,表示這個執行個體的值是衍生類別的預設值。When overridden in a derived class, indicates whether the value of this instance is the default value for the derived class.

(繼承來源 Attribute)
Match(Object)

在衍生類別中覆寫時,會傳回值,表示這個執行個體是否等於指定物件。When overridden in a derived class, returns a value that indicates whether this instance equals a specified object.

(繼承來源 Attribute)
MemberwiseClone()

建立目前 Object 的淺層複本 (Shallow Copy)。Creates a shallow copy of the current Object.

(繼承來源 Object)
ToString()

傳回代表目前物件的字串。Returns a string that represents the current object.

(繼承來源 Object)

明確介面實作

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

將一組名稱對應至一組對應的分派識別項 (Dispatch Identifier)。Maps a set of names to a corresponding set of dispatch identifiers.

(繼承來源 Attribute)
_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

擷取物件的類型資訊,可以用來取得介面的類型資訊。Retrieves the type information for an object, which can be used to get the type information for an interface.

(繼承來源 Attribute)
_Attribute.GetTypeInfoCount(UInt32)

擷取物件提供的類型資訊介面數目 (0 或 1)。Retrieves the number of type information interfaces that an object provides (either 0 or 1).

(繼承來源 Attribute)
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

提供物件所公開的屬性和方法的存取權。Provides access to properties and methods exposed by an object.

(繼承來源 Attribute)

適用於

另請參閱