WCF: Serializing and Deserializing generic collections

后端 未结 4 1306
青春惊慌失措
青春惊慌失措 2020-12-10 01:25

I have a class Team that holds a generic list:

[DataContract(Name = \"TeamDTO\", IsReference = true)]
public class Team
{
    [DataMember]
    private IList&         


        
4条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-10 02:15

    You've run into one of the DataContractSerializer gotchas.

    Fix: Change your private member declaration to:

    [DataMember]
    private List members = new List();
    

    OR change the property to:

    [DataMember()]
    public IList Feedback {
        get { return m_Feedback; }
        set {
            if ((value != null)) {
                m_Feedback = new List(value);
    
            } else {
                m_Feedback = new List();
            }
        }
    }
    

    And it will work. The Microsoft Connect bug is here

    This problem occurs when you deserialize an object with an IList DataMember and then try to serialize the same instance again.

    If you want to see something cool:

    using System;
    using System.Collections.Generic;
    
    class TestArrayAncestry
    {
        static void Main(string[] args)
        {
            int[] values = new[] { 1, 2, 3 };        
            Console.WriteLine("int[] is IList: {0}", values is IList);
        }
    }
    

    It will print int[] is IList: True.

    I suspect this is possibly the reason you see it come back as an array after deserialization, but it is quite non-intuitive.

    If you call the Add() method on the IList of the array though, it throws NotSupportedException.

    One of those .NET quirks.

提交回复
热议问题