共用方式為


資料成員順序

在某些應用程式中,知道來自各個資料成員之資料的傳送順序或是資料的預期收到順序是十分有用的 (例如,資料出現在序列化 XML 中的順序)。有時候可能需要變更這個順序。本主題將說明排序規則。

基本規則

資料排序的基本規則包括:

  • 如果資料合約類型屬於繼承階層的一部分,則其基底類型的資料成員順序一定會是最前面。

  • 順序接著為目前類型的資料成員,該成員不具有以字母順序顯示之 DataMemberAttribute 屬性 (Attribute) 集的 Order 屬性 (Property)。

  • 順序接著為不具有 DataMemberAttribute 屬性 (Attribute) 集之 Order 屬性 (Property) 的任何資料成員。這些成員會先依據 Order 屬性的值排序,如果有一個以上的成員擁有特定的 Order 值才會以字母排序。Order 屬性值可以略過。

透過呼叫 CompareOrdinal 方法,即可建立字母順序。

範例

請考慮下列程式碼:

<DataContract()> _
Public Class BaseType
    <DataMember()> Public zebra As String
End Class

<DataContract()> _
Public Class DerivedType
    Inherits BaseType
    <DataMember(Order:=0)> Public bird As String
    <DataMember(Order:=1)> Public parrot As String
    <DataMember()> Public dog As String
    <DataMember(Order:=3)> Public antelope As String
    <DataMember()> Public cat As String
    <DataMember(Order:=1)> Public albatross As String
End Class
[DataContract]
public class BaseType
{

    [DataMember]
    public string zebra;
}
[DataContract]
public class DerivedType : BaseType
{
    [DataMember(Order = 0)]
    public string bird;
    [DataMember(Order = 1)]
    public string parrot;
    [DataMember]
    public string dog;
    [DataMember(Order = 3)]
    public string antelope;
    [DataMember]
    public string cat;
    [DataMember(Order = 1)]
    public string albatross;
}

產生的 XML 如下所示。

<DerivedType>
    <!-- Zebra is a base data member, and appears first. -->
    <zebra/> 

    <!-- Cat has no Order, appears alphabetically first. -->
    <cat/>
    
   <!-- Dog has no Order, appears alphabetically last. -->
    <dog/> 

    <!-- Bird is the member with the smallest Order value -->
    <bird/>

    <!-- Albatross has the next Order value, alphabetically first. -->
    <albatross/>

    <!-- Parrot, with the next Order value, alphabetically last. -->
     <parrot/>

    <!-- Antelope is the member with the highest Order value. Note that 
    Order=2 is skipped -->
     <antelope/> 
</DerivedType>

另請參閱

參考

DataContractAttribute

概念

資料合約等價
使用資料合約