在某些應用程式中,瞭解從各種資料成員傳送或預期接收數據的順序很有用(例如數據出現在串行化 XML 中的順序)。 有時候可能需要變更此順序。 本主題說明排序規則。
基本規則
資料排序的基本規則包括:
如果資料合約型別是繼承階層的一部分,其基礎類型的資料成員一律最先排列。
接下來是目前類型的數據成員,其中屬性集未設定Order屬性DataMemberAttribute的依字母順序排列。
接下來是具有 Order 屬性集屬性 DataMemberAttribute 的任何數據成員。 這些項目首先按照
Order
屬性的值進行排序,若特定Order
值有多個成員,則按字母順序排列。 可以跳過訂單金額。
依字母順序建立的方式是呼叫 CompareOrdinal 方法。
範例
請考慮下列程序代碼。
[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;
}
<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
產生的 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>