本文為機器翻譯文章。如需檢視英文版,請選取 [原文] 核取方塊。您也可以將滑鼠指標移到文字上,即可在快顯視窗顯示英文原文。
譯文
原文

DataContractAttribute 類別

 

指定定義或實作資料合約的型別,可由序列化程式 (例如 DataContractSerializer) 加以序列化。 型別作者一定要定義型別的資料合約,才能讓型別能夠進行序列化。

命名空間:   System.Runtime.Serialization
組件:  System.Runtime.Serialization (於 System.Runtime.Serialization.dll)

System.Object
  System.Attribute
    System.Runtime.Serialization.DataContractAttribute

[AttributeUsageAttribute(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum, 
	Inherited = false, AllowMultiple = false)]
public sealed class DataContractAttribute : Attribute

名稱描述
System_CAPS_pubmethodDataContractAttribute()

初始化 DataContractAttribute 類別的新執行個體。

名稱描述
System_CAPS_pubpropertyIsNameSetExplicitly

取得是否已明確設定 Name

System_CAPS_pubpropertyIsNamespaceSetExplicitly

取得是否已明確設定 Namespace

System_CAPS_pubpropertyIsReference

取得或設定值,這個值表示是否要保留物件參考資料。

System_CAPS_pubpropertyIsReferenceSetExplicitly

取得是否已明確設定 IsReference

System_CAPS_pubpropertyName

取得或設定型別的資料合約名稱。

System_CAPS_pubpropertyNamespace

取得或設定型別之資料合約的命名空間。

System_CAPS_pubpropertyTypeId

在衍生類別中實作時,取得這個 Attribute 的唯一識別碼。(繼承自 Attribute。)

名稱描述
System_CAPS_pubmethodEquals(Object)

此 API 支援 產品 基礎結構,而且不適合直接從程式碼使用。 傳回值,這個值指出此執行個體是否與指定的物件相等。(繼承自 Attribute。)

System_CAPS_pubmethodGetHashCode()

傳回這個執行個體的雜湊碼。(繼承自 Attribute。)

System_CAPS_pubmethodGetType()

取得目前執行個體的 Type(繼承自 Object。)

System_CAPS_pubmethodIsDefaultAttribute()

在衍生類別中覆寫時,表示這個執行個體的值是衍生類別的預設值。(繼承自 Attribute。)

System_CAPS_pubmethodMatch(Object)

當在衍生類別中覆寫時,傳回值,指出這個執行個體是否等於指定的物件。(繼承自 Attribute。)

System_CAPS_pubmethodToString()

傳回代表目前物件的字串。(繼承自 Object。)

名稱描述
System_CAPS_pubinterfaceSystem_CAPS_privmethod_Attribute.GetIDsOfNames(Guid, IntPtr, UInt32, UInt32, IntPtr)

將一組名稱對應至一組對應的分派識別項 (Dispatch Identifier)。(繼承自 Attribute。)

System_CAPS_pubinterfaceSystem_CAPS_privmethod_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr)

擷取物件的類型資訊,可以用來取得介面的類型資訊。(繼承自 Attribute。)

System_CAPS_pubinterfaceSystem_CAPS_privmethod_Attribute.GetTypeInfoCount(UInt32)

擷取物件提供的類型資訊介面數目 (0 或 1)。(繼承自 Attribute。)

System_CAPS_pubinterfaceSystem_CAPS_privmethod_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr)

提供物件所公開的屬性和方法的存取權。(繼承自 Attribute。)

Apply the T:System.Runtime.Serialization.DataContractAttribute attribute to types (classes, structures, or enumerations) that are used in serialization and deserialization operations by the T:System.Runtime.Serialization.DataContractSerializer. If you send or receive messages by using the indigo1 infrastructure, you should also apply the T:System.Runtime.Serialization.DataContractAttribute to any classes that hold and manipulate data sent in messages. crabout data contracts, see Using Data Contracts.

You must also apply the T:System.Runtime.Serialization.DataMemberAttribute to any field, property, or event that holds values you want to serialize. By applying the T:System.Runtime.Serialization.DataContractAttribute, you explicitly enable the T:System.Runtime.Serialization.DataContractSerializer to serialize and deserialize the data.

System_CAPS_caution注意

You can apply the T:System.Runtime.Serialization.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.

如需詳細資訊 data contracts, see the topics listed in 使用資料合約.

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. For example, the data contract may call for a data type named "Person" that has two text fields, named "FirstName" and "LastName". To create a data contract, apply the T:System.Runtime.Serialization.DataContractAttribute to the class and apply the T:System.Runtime.Serialization.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.

System_CAPS_note注意

A data contract differs significantly from an actual interface in its inheritance behavior. Interfaces are inherited by any derived types. When you apply the T:System.Runtime.Serialization.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. However, you must apply the T:System.Runtime.Serialization.DataMemberAttribute to new members in a derived class to make them serializable.

If you are exchanging data with other services, you must describe the data contract. For the current version of the T:System.Runtime.Serialization.DataContractSerializer, an XML schema can be used to define data contracts. (Other forms of metadata/description could be used for the same purpose.) To create an XML schema from your application, use the Service Model Metadata Utility Tool (Svcutil.exe) with the /dconly command line option. 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. 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. In this case, the /dconly command line option is not required.

If the input to the Svcutil.exe tool is an XML schema, by default, the tool creates a set of classes. If you examine those classes, you find that the T:System.Runtime.Serialization.DataContractAttribute has been applied. You can use those classes to create a new application to process data that must be exchanged with other services.

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 indigo1 client. The generated code includes types that are marked with the T:System.Runtime.Serialization.DataContractAttribute.

A data contract has two basic requirements: a stable name and a list of members. The stable name consists of the namespace uniform resource identifier (URI) and the local name of the contract. By default, when you apply the T:System.Runtime.Serialization.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. You can override the defaults by setting the P:System.Runtime.Serialization.DataContractAttribute.Name and P:System.Runtime.Serialization.DataContractAttribute.Namespace properties. You can also change the namespace by applying the T:System.Runtime.Serialization.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.

System_CAPS_note注意

In any code, you can use the word DataContract instead of the longer T:System.Runtime.Serialization.DataContractAttribute.

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. To do this, implement the T:System.Runtime.Serialization.IExtensibleDataObject interface.

如需詳細資訊 versioning, see 資料合約版本控制.

The following example serializes and deserializes a class named Person to which the T:System.Runtime.Serialization.DataContractAttribute has been applied. Note that the P:System.Runtime.Serialization.DataContractAttribute.Namespace and P:System.Runtime.Serialization.DataContractAttribute.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();
        }

    }
}

通用 Windows 平台
自 8 起供應
.NET Framework
自 3.0 起供應
可攜式類別庫
提供支援︰ 可攜式 .NET 平台
Silverlight
自 2.0 起供應
Windows Phone Silverlight
自 7.0 起供應
Windows Phone
自 8.1 起供應

此類型的任何 public static (在 Visual Basic 中 共用 在 Visual Basic 中) 成員皆為安全執行緒。不保證任何執行個體成員為安全執行緒。

回到頁首
顯示: