承上篇泛型資料契約,本文聚焦集合型別的序列化規則、自訂集合契約(CollectionDataContractAttribute)、字典型別處理,以及 Visual Studio 服務參考導入時的集合型別客製化選項。
三者序列化結果完全一致:根節點 ArrayOf{ElementType},命名空間沿用元素契約,元素按契約序列化。預設導入 Client 端皆轉為陣列 T[]。
VS 導入客製化: 「加入服務參考」→「進階」→「集合類型」可選:Array、ArrayList、LinkedList、GenericList(List<T>)、Collection、BindingList。選 GenericList 後導入介面參數型別皆為 List<Customer>。
元素型別不可知,序列化根節點為 ArrayOfanyType,元素節點 anyType,含 i:type 指定實際型別。必須將潛在元素型別加入 DataContractSerializer 的 knownTypes,否則失敗。導入 Client 端轉為 object[],同樣可透過 VS 設定改為 List<object>。
繼承 List<T> 或實作 IEnumerable<T> 並具備:
InvalidDataContractExceptionCollectionDataContractAttribute 可自訂:
Name、Namespace:契約名稱/空間ItemName:元素節點名稱(預設元素契約名)KeyName、ValueName:字典型集合的 Key/Value 節點名範例: CustomerCollection 設定 Name="CustomerList"、ItemName="CustomerEntry",輸出 <CustomerList><CustomerEntry>...。
元素為 KeyValuePair<TKey,TValue>。泛型字典根節點含型別哈希值(如 ArrayOfKeyValueOfguidCustomer2af2CULK);Hashtable 為 ArrayOfKeyValueOfanyTypeanyType。導入 Client 端:Hashtable→Dictionary<object,object>,泛型字典保留泛型參數。
VS 字典集合類型選項更豐富:Dictionary、Hashtable、SortedList、GenericDictionary 等。
自訂字典契約: 繼承 Dictionary<TKey,TValue> 標註 CollectionDataContract 設定 ItemName、KeyName、ValueName,輸出清晰語意化 XML:<CustomerCollection><CustomerEntry><CustomerID>...<Customer>...。