数据成员顺序

在一些应用程序中,有必要知道各个数据成员中数据的发送顺序或预期接收顺序(比如序列化 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

概念

数据协定等效性
使用数据协定