【问题标题】:WCF serialization and IEnumerable<T> vs ICollection<T> inheritanceWCF 序列化和 IEnumerable<T> 与 ICollection<T> 继承
【发布时间】:2013-06-26 20:28:19
【问题描述】:

我知道在创建继承自 List&lt;T&gt;ICollection&lt;T&gt; 并带有其他自定义属性的自定义集合时会出现问题:

public class MyCollection: List<int>
{
    public string MyCustomProperty { get; set; }
}

据我所知,此类集合将通过 throw WCF 作为 ArrayOfInt 并且 WCF 不会序列化我的自定义属性。解决方案是创建将管理内部集合并具有自定义属性的包装类。

我想根据自己的需要制定一个更好的解决方法...IEnumerable&lt;T&gt; 会遇到同样的问题吗?

public class MyCollection: IEnumerable<int>
{
   /**************/
   /* Code that implements IEnumerable<int> and manages the internal List<T> */
   /* I know I will not able to cast it to List<T>, but I don't need it.  */
   /* If I will need it, I will implement cast operators later */
   /**************/

   public string MyCustomProperty { get; set; }
}

上面的类是否会通过 throw WCF 包含 MyCustomProperty 值?

谢谢

【问题讨论】:

    标签: wcf serialization ienumerable icollection


    【解决方案1】:

    我试过了,它没有序列化自定义属性。 我刚刚从服务方法返回了整个类对象。结果仍然是 ArrayOfInt(我使用 List 作为容器)

    public class MyExtension: IEnumerable<int>
    {
        public string CustomString { get; set; }
        private List<int> lst = new List<int>(); 
    
        public void Add(int i)
        {
            lst.Add(i);
        }
    
        public IEnumerator<int> GetEnumerator()
        {
            return lst.GetEnumerator();
        }
    
        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return lst.GetEnumerator();
        }
    }
    

    我必须将其标记为 DataContract 并将每个成员标记为 DataMember 才能序列化所有属性。

    <MyExtension xmlns="http://schemas.datacontract.org/2004/07/GetRequestTest"     xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
     <CustomString>sunny</CustomString> 
     <lst xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
        <a:int>1</a:int> 
     </lst>
    </MyExtension>
    

    【讨论】:

    • 但是在你标记为DataMember之后,它会返回一个自定义属性,所以它是解决方案,因为使用ICollection,即使标记为DataMember,该属性也不会通过。
    • 顺便说一句,我想我发现如果一个类将被标记为可序列化而不是 DataContract,那么它甚至可以使用 ICollection,但我还没有很好地测试它。跨度>
    • 而且我相信您为 List 创建了一个属性,以便能够将其标记为 DataMember,因为私有字段未使用 DataContract 序列化。还是我错了?
    • 私有字段可通过 DataMember 属性进行序列化。是的,您可以通过 Serializable 属性完成序列化,但我认为 DataContract 更快。请。参考这篇文章-stackoverflow.com/questions/4792269/…
    猜你喜欢
    • 2010-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-29
    • 1970-01-01
    • 2021-04-16
    相关资源
    最近更新 更多