在某些应用程序中,了解从各种数据成员发送或应接收数据的顺序(例如数据在序列化 XML 中显示的顺序)非常有用。 有时可能需要更改此顺序。 本主题介绍排序规则。
基本规则
数据排序的基本规则包括:
如果数据契约类型是继承层次结构的一部分,其基类型的数据成员始终优先排列。
排在下一位的是当前类型的数据成员(按字母顺序排列),这些成员未设置 Order 属性 (attribute) 的 DataMemberAttribute 属性 (property)。
再下面是设置了 Order 属性 (attribute) 的 DataMemberAttribute 属性 (property) 的任何数据成员。 这些属性先按属性的值
Order
排序,然后按字母顺序排序(如果存在特定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>