首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> 關於.NET

談 WCF Data Contract (三):集合與字典型別的序列化支援

     編輯:關於.NET

前言

上一篇提到 IList<TDetail> 在資料合約中呈現為陣列。本文詳細探討 WCF 對集合 (Collection) 與字典 的支援,以及用戶端 Proxy 產生時的型別對應選項。

一、集合型別的資料合約

1.1 定義集合類別


[DataContract]
public class Order
{
    [DataMember] public Guid OrderID { get; set; }
    [DataMember] public DateTime OrderDate { get; set; }
}

public class OrderCollection : List<Order> { }

1.2 服務合約


[ServiceContract]
public interface IOrderManager
{
    [OperationContract(Name = "ProcessWithCollection")]
    void Process(OrderCollection orders);
}

1.3 XSD 呈現

WCF 將 OrderCollection 序列化為 ArrayOfOrder 複雜型別:


<xs:complexType name="ArrayOfOrder">
  <xs:sequence>
    <xs:element minOccurs="0" maxOccurs="unbounded" name="Order" nillable="true" type="tns:Order" />
  </xs:sequence>
</xs:complexType>

預設產生的用戶端 Proxy 參數為陣列:Order[] orders。

1.4 用戶端集合型別自訂

在 Visual Studio「設定服務參考」對話框中,可選擇集合對應型別:

  • Array (預設)
  • ArrayList
  • LinkedList
  • Generic List (List<T>) — 最常用
  • Collection
  • BindingList (支援資料繫結)

集合型別選項

選擇 List<T> 後,Proxy 簽名變為 List<Order> orders,更符合 .NET 開發習慣。

二、字典型別的資料合約

2.1 服務合約加入字典操作


[ServiceContract]
public interface IOrderManager
{
    [OperationContract(Name = "ProcessWithDictionary")]
    void Process(IDictionary<Guid, Order> orders);
}

2.2 XSD 呈現

字典序列化為 ArrayOfKeyValueOf<KeyType><ValueType><Hash>,結構為鍵值對陣列:


<xs:complexType name="ArrayOfKeyValueOfguidOrder_SkVQi6O3">
  <xs:annotation>
    <xs:appinfo>
      <IsDictionary xmlns="https://schemas.microsoft.com/2003/10/Serialization/">true</IsDictionary>
    </xs:appinfo>
  </xs:annotation>
  <xs:sequence>
    <xs:element minOccurs="0" maxOccurs="unbounded" name="KeyValueOfguidOrder_SkVQi6O3">
      <xs:complexType>
        <xs:sequence>
          <xs:element name="Key" type="ser:guid"/>
          <xs:element name="Value" nillable="true" type="q1:Order"/>
        </xs:sequence>
      </xs:complexType>
    </xs:element>
  </xs:sequence>
</xs:complexType>

IsDictionary 標記告知序列化器此為字典結構。

2.3 用戶端字典型別自訂

同樣在「設定服務參考」中可選擇字典對應型別:

  • Dictionary<TKey, TValue> (預設)
  • Hashtable
  • SortedList<TKey, TValue>
  • KeyedCollection<TKey, TValue>
  • 自訂實作 IDictionary<TKey, TValue> 的型別

三、核心原理與注意事項

特性集合字典
序列化結構元素陣列鍵值對陣列 (含 IsDictionary 標記)
預設 Proxy 型別Array (T[])Dictionary<TKey, TValue>
可自訂 Proxy 型別是 (6 種選項)是 (5 種選項)
介面支援IList、ICollection、IEnumerableIDictionary
自訂集合類別繼承 List<T> 或 Collection<T>繼承 Dictionary<TKey, TValue>

最佳實務

  • 服務合約參數建議使用介面型別 (IList<T>、IDictionary<TKey, TValue>),實作類別可為具體集合。
  • 用戶端專案統一設定集合對應為 List<T>、字典對應為 Dictionary<TKey, TValue>,提升開發一致性。
  • 自訂集合類別需標記 [CollectionDataContract] 以控制項目名稱、命名空間等。
  • 避免在資料合約中使用 ArrayList、Hashtable 等非泛型集合,會導致型別資訊遺失。

結語

WCF 透過標準化的 XSD 表示集合與字典,並提供豐富的用戶端型別對應選項,滿足不同開發需求。下一篇將探討泛型型別的資料合約支援。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved