WCF集合數(shù)據(jù)契約相關(guān)定制方法詳解
WCF集合數(shù)據(jù)契約的定制方法在實(shí)際操作中是一個(gè)比較基礎(chǔ)的應(yīng)用技術(shù)。我們可以使用CollectionDataContractAttribute的下列屬性來指定WCF集合數(shù)據(jù)契約的相關(guān)名稱及命名空間:#t#
Name屬性來指定集合數(shù)據(jù)契約的名稱(如果沒有使用此屬性,將使用集合類型的名稱)
Namespace屬性來指定其命名空間
ItemName 屬性來指定循環(huán)元素的名稱
針對字典集合還可以用KeyName和ValueName來指定鍵和值的名稱
WCF集合數(shù)據(jù)契約示例所示:
- [CollectionDataContract(Name = "telephones", ItemName = "telephone",
- KeyName = "Index", ValueName = "Number")]
- public class MyDictionary : Dictionary< int, object>
- {
- public new Dictionary< int,object>.Enumerator GetEnumerator()
- {
- Dictionary< int, object> innerObject = new Dictionary< int, object> {
- { 1, "010-82371234" },
- { 2, "021-56781234" } };
- return innerObject.GetEnumerator();
- }
- }
此類將被序列化成:
- < telephones xmlns:i=http://www.w3.org/2001/XMLSchema-instance
xmlns="http://schemas.datacontract.org/2004/07/WCFTestSerializer">- < telephone>
- < Index>1< /Index>
- < Number xmlns:d4p1=http://www.w3.org/2001/XMLSchema
i:type="d4p1:string">010-82371234< /Number>- < /telephone>
- < telephone>
- < Index>2< /Index>
- < Number xmlns:d4p1=http://www.w3.org/2001/XMLSchema
i:type="d4p1:string">021-56781234< /Number>- < /telephone>
- < /telephones>
對于定制WCF集合數(shù)據(jù)契約來說,前面所述的非定制數(shù)據(jù)契約的集合等價(jià)規(guī)則將失效。所以要盡量避免使用CollectionDataContractAttribute。