WCF中的自定义集合

WCF Tips之一

集合元素类的定义如下:
    public enum FileType
    {
        TXT,DOC,HTML,OTHER
    }
    [DataContract]
    
public class Document
    {
        
private string m_localPath;
        
private string m_fileName;
        
private FileType m_fileType;        

        [DataMember]
        
public string LocalPath
        {
            
get { return m_localPath; }
            
set { m_localPath = value; }
        }

        [DataMember]
        
public string FileName
        {
            
get { return m_fileName; }
            
set { m_fileName = value; }
        }
        [DataMember]
        
public FileType FileType
        {
            
get { return m_fileType; }
            
set { m_fileType = value; }
        }

    }

自定义集合DocumentList则实现了IList<Document>接口:

注意,对于自定义集合DocumentList而言,我们不能应用[DataContract]特性,否则会在服务操作中无法返回正确的DocumentList对象。例如如下的服务操作定义,实际上无法获得正确的DocumentList值:
        [OperationContract]
        [FaultContract(
typeof(DirectoryNotFoundException))]
        DocumentList FetchDocuments(
string homeDir);

我们应该为DocumentList施加[CollectionDataContract]或者[Serializable],建议采用前者。因为对于自定义集合而言,如果是泛型集合,还可以利用Name属性制定导出元数据生成的类型名。不过,对于本例的集合而言,由于没有泛型参数,则无所谓了。为了在导出元数据时识别集合的元素Document类型,当然,还需要施加KnowTypeAttribute,最后的定义修改如下:
    [KnownType(typeof(Document))]
    [CollectionDataContract]  
    [Serializable]
    
public class DocumentList:IList<Document>
    {}

此时,客户端应用程序可以直接使用数据契约,仍然能够识别。

posted on 2007-11-02 16:06 张逸 阅读(2134) 评论(3)  编辑 收藏 所属分类: WCF & SOAWCF Tips

评论

#1楼  2007-11-08 13:43 学习人 [未注册用户]

在服务器端的一个方法是Hashtable 类型,为什么生的client是:ArrayOfKeyValueOfanyTypeanyTypeKeyValueOfanyTypeanyType[]
我怎么处理呢?   回复  引用    

#2楼  2007-11-11 09:43 Betree Xing      

老大, 最近你的博客的页面用IE打开, 在加载完成时, 就会提示 "Internet Explorer 无法打开Internet 站点, Http://www.cnblogs.com/*****.html
已终止操作", 点击"确定"按钮之后, 就会转向错误信息页面了, 小弟揣测可能是某个外部引用的资源(js, css等)不可用了, 你有空检查一下哦,
偶是用ff给你写的留言.
  回复  引用  查看    

#3楼 [楼主] 2007-11-12 11:21 Bruce Zhang      

@Betree Xing
我前段时间就发现了这一问题,正在联系dudu帮我解决。

目前,使用FireFox浏览我的博客没有任何问题。   回复  引用  查看    

导航

公告

logo.gif
我的著作与译作

《软件设计精要与模式》

《WCF服务编程》

MVP_Horizontal_BlueOnly.png

From 03-03-2006
Counter: site stats

与我联系

常用链接

我参加的小组

我参与的团队

随笔分类(244)

随笔档案(235)

最新随笔

搜索

积分与排名

最新评论

阅读排行榜

评论排行榜