WCF集合数据契约相关定制方法详解

WCF集合数据契约的定制方法在实际操作中是一个比较基础的应用技术。我们可以使用CollectionDataContractAttribute的下列属性来指定WCF集合数据契约的相关名称及命名空间:#t#

Name属性来指定集合数据契约的名称(如果没有使用此属性,将使用集合类型的名称)

Namespace属性来指定其命名空间

ItemName 属性来指定循环元素的名称

针对字典集合还可以用KeyName和ValueName来指定键和值的名称

WCF集合数据契约示例所示:

 

 
 
 
  1. [CollectionDataContract(Name = "telephones"ItemName = "telephone",  
  2. KeyName = "Index"ValueName = "Number")]  
  3. public class MyDictionary : Dictionary< int, object> 
  4. {  
  5. public new Dictionary< int,object>.Enumerator GetEnumerator()  
  6. {  
  7. Dictionary< int, object> innerObject = new Dictionary< int, object> {  
  8. { 1, "010-82371234" },   
  9. { 2, "021-56781234" } };  
  10. return innerObject.GetEnumerator();  
  11. }  

 

此类将被序列化成:

 

 
 
 
  1. < telephones xmlns:i=http://www.w3.org/2001/XMLSchema-instance 
    xmlns="http://schemas.datacontract.org/2004/07/WCFTestSerializer"> 
  2. < telephone> 
  3. < Index>1< /Index> 
  4. < Number xmlns:d4p1=http://www.w3.org/2001/XMLSchema 
    i:type="d4p1:string">010-82371234< /Number> 
  5. < /telephone> 
  6. < telephone> 
  7. < Index>2< /Index> 
  8. < Number xmlns:d4p1=http://www.w3.org/2001/XMLSchema 
    i:type="d4p1:string">021-56781234< /Number> 
  9. < /telephone> 
  10. < /telephones> 

 

对于定制WCF集合数据契约来说,前面所述的非定制数据契约的集合等价规则将失效。所以要尽量避免使用CollectionDataContractAttribute。

THE END