上一篇提到 IList<TDetail> 在資料合約中呈現為陣列。本文詳細探討 WCF 對集合 (Collection) 與字典 的支援,以及用戶端 Proxy 產生時的型別對應選項。
[DataContract]
public class Order
{
[DataMember] public Guid OrderID { get; set; }
[DataMember] public DateTime OrderDate { get; set; }
}
public class OrderCollection : List<Order> { }
[ServiceContract]
public interface IOrderManager
{
[OperationContract(Name = "ProcessWithCollection")]
void Process(OrderCollection orders);
}
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。
在 Visual Studio「設定服務參考」對話框中,可選擇集合對應型別:
List<T>) — 最常用
選擇 List<T> 後,Proxy 簽名變為 List<Order> orders,更符合 .NET 開發習慣。
[ServiceContract]
public interface IOrderManager
{
[OperationContract(Name = "ProcessWithDictionary")]
void Process(IDictionary<Guid, Order> orders);
}
字典序列化為 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 標記告知序列化器此為字典結構。
同樣在「設定服務參考」中可選擇字典對應型別:
Dictionary<TKey, TValue> (預設)HashtableSortedList<TKey, TValue>KeyedCollection<TKey, TValue>IDictionary<TKey, TValue> 的型別| 特性 | 集合 | 字典 |
|---|---|---|
| 序列化結構 | 元素陣列 | 鍵值對陣列 (含 IsDictionary 標記) |
| 預設 Proxy 型別 | Array (T[]) | Dictionary<TKey, TValue> |
| 可自訂 Proxy 型別 | 是 (6 種選項) | 是 (5 種選項) |
| 介面支援 | IList、ICollection、IEnumerable | IDictionary |
| 自訂集合類別 | 繼承 List<T> 或 Collection<T> | 繼承 Dictionary<TKey, TValue> |
IList<T>、IDictionary<TKey, TValue>),實作類別可為具體集合。List<T>、字典對應為 Dictionary<TKey, TValue>,提升開發一致性。[CollectionDataContract] 以控制項目名稱、命名空間等。ArrayList、Hashtable 等非泛型集合,會導致型別資訊遺失。WCF 透過標準化的 XSD 表示集合與字典,並提供豐富的用戶端型別對應選項,滿足不同開發需求。下一篇將探討泛型型別的資料合約支援。