次の方法で共有


データ メンバーの順序

一部のアプリケーションでは、各種のデータ メンバーから送信される、または受信されると予想できるデータの順序 (たとえばシリアル化された XML でデータが表れる順序) がわかると便利です。この順序を変更する必要が生じることもあります。ここでは、このような順序を決定する規則について説明します。

基本的な規則

データの順序を決定する基本的な規則には、次のようなものがあります。

  • データ コントラクト型が継承階層の一部である場合、その基本型のデータ メンバーが常に最初の順番になります。

  • 次に来るのは DataMemberAttribute 属性の Order プロパティが設定されていない、現在の型のデータ メンバー (アルファベット順) になります。

  • その次に来るのは、DataMemberAttribute 属性の Order プロパティが設定されているすべてのデータ メンバーです。これらのデータ メンバーはまず 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

概念

データ コントラクトの等価性
データ コントラクトの使用