DataContractAttribute 類別
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
指定定義或實作資料合約的型別,可由序列化程式 (例如 DataContractSerializer) 加以序列化。 型別作者一定要定義型別的資料合約,才能讓型別能夠進行序列化。
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
- 繼承
- 屬性
範例
下列範例會序列化和還原序列化名稱為 Person
且已套用 DataContractAttribute 的類別。 請注意,Namespace 和 Name 屬性的值已經設定為將覆寫預設設定。
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) 作業中所使用的型別 (類別、結構或列舉)。 如果您使用 Windows Communication Foundation (WCF) 基礎結構來傳送或接收訊息,則也應該將 套用 DataContractAttribute 至任何保存及操作訊息中所傳送資料的類別。 如需資料合約的詳細資訊,請參閱 使用資料合約。
您也必須將 DataMemberAttribute 套用至負責保存您要序列化之值的任何欄位、屬性或事件。 透過套用 DataContractAttribute,您便可以明確地讓 DataContractSerializer 能夠序列化和還原序列化資料。
警告
您可以將 DataMemberAttribute 套用至私用欄位。 請注意,此欄位 (即使它是私用欄位) 傳回的資料會進行序列化和還原序列化,因此可能會遭到惡意使用者或處理序的檢視或攔截。
如需資料合約的詳細資訊,請參閱 使用資料合約中所列的主題。
資料合約
資料合約 是一組欄位的抽象描述,其中包含每個欄位的名稱和資料類型。 資料合約存在於任何單一實作之外,以便讓不同平台上的服務能夠相互操作。 只要在服務之間傳遞的資料符合相同的合約,所有服務就能夠處理該份資料。 此處理也稱為 鬆散結合的系統。 資料合約也類似一種介面,而在這種介面中,合約會指定資料必須如何傳遞才可讓應用程式加以處理。 例如,資料合約可能會要求名為 "Person" 並包含兩個名稱分別為 "FirstName" 和 "LastName" 之文字欄位的資料型別。 若要建立資料合約,請將 DataContractAttribute 套用至類別,並將 DataMemberAttribute 套用至必須進行序列化的任何欄位或屬性。 當完成序列化之後,資料就會符合已在該型別中隱含內建的資料合約。
注意
就繼承行為來看,資料合約與實際的介面有很大的不同。 介面是繼承自任何衍生的型別。 當您將 DataContractAttribute 套用至基底類別時,衍生的型別並不會繼承屬性或行為。 但是,如果衍生的型別擁有資料合約,該基底類別的資料成員就會進行序列化。 但是您必須將 DataMemberAttribute 套用至衍生類別的新成員,才能讓這些成員進行序列化。
XML 結構描述文件和 SvcUtil 工具
如果您要與其他服務交換資料,就必須描述資料合約。 若是最新版本的 DataContractSerializer,則可以使用 XML 結構描述來定義資料合約 (其他形式的中繼資料/描述可用於相同的用途。) 若要從您的應用程式建立 XML 架構,請使用 ServiceModel 中繼資料公用程式工具 (Svcutil.exe) 搭配 /dconly 命令列選項。 根據預設,如果工具的輸入項目是組件時,工具就會產生 XML 結構描述集合,而此集合會定義在該組件中找到的所有資料合約型別。 相反地,您也可以使用 Svcutil.exe 工具來建立符合 XML 結構描述需求的 Visual Basic 或 C# 類別定義,而這些結構描述會使用能夠透過資料合約表示的建構。 在此情況下,不需要 /dconly 命令列選項。
根據預設,如果 Svcutil.exe 工具的輸入項目是 XML 結構描述,工具就會建立類別集合。 如果您檢查這些類別,您就會發現此時已套用了 DataContractAttribute。 您可以使用這些類別來建立新的應用程式,以便處理必須與其他服務交換的資料。
您也可以針對傳回 Web 服務描述語言 (WSDL) 檔的端點執行此工具,以自動產生程式碼和組態,以建立 Windows Communication Foundation (WCF) 用戶端。 所產生的程式碼會包含以 DataContractAttribute 標記的型別。
重複使用現有的型別
資料合約有兩項基本要求,一個是穩定的名稱,另一個則是成員的清單。 穩定的名稱是由命名空間統一資源識別元 (URI) 以及合約的本機名稱組成。 根據預設,當您將 套用 DataContractAttribute 至類別時,它會使用類別名稱作為本機名稱,而類別的命名空間 (前面 "http://schemas.datacontract.org/2004/07/"
加上) 作為命名空間 URI。 您可以藉由設定 Name 和 Namespace 屬性來覆寫預設值。 您也可以藉由將 ContractNamespaceAttribute 套用至命名空間以變更命名空間。 當現有的型別能夠完全依照需求處理資料,但卻擁有與資料合約不同的命名空間和類別名稱時,您就可以使用這項功能。 藉由覆寫預設值,您就可以重複使用現有的型別,並使已序列化的資料符合資料合約。
注意
您可以在任何程式碼中使用 DataContract
一字來代替較長的 DataContractAttribute。
版本控制
資料合約也能配合本身的較新版本。 也就是說,當合約的較新版本含有其他資料時,這時會儲存該份資料,然後將其原封不動地傳回給傳送者。 若要執行這個步驟,請實作 IExtensibleDataObject 介面。
如需版本控制的詳細資訊,請參閱 資料合約版本設定。
建構函式
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) |
將一組名稱對應至一組對應的分派識別項 (Dispatch Identifier)。 (繼承來源 Attribute) |
_Attribute.GetTypeInfo(UInt32, UInt32, IntPtr) |
擷取物件的類型資訊,可以用來取得介面的類型資訊。 (繼承來源 Attribute) |
_Attribute.GetTypeInfoCount(UInt32) |
擷取物件提供的類型資訊介面數目 (0 或 1)。 (繼承來源 Attribute) |
_Attribute.Invoke(UInt32, Guid, UInt32, Int16, IntPtr, IntPtr, IntPtr, IntPtr) |
提供物件所公開的屬性和方法的存取權。 (繼承來源 Attribute) |