如何将List <t>反序列化为另一个List <t>而不是readonly T []?</t> </t>

时间:2014-06-23 14:11:22

标签: c# datacontractserializer

我们有一些代码可以复制List<T>个对象。问题是代码返回的是T[]而不是List<T>的只读数组。

为什么会这样,以及如何修复此反序列化代码?

public interface ITestObject { }

[KnownType(typeof(ITestObject))]
[DataContract(Name = "TestObject")]
public class TestObject : ITestObject
{
    [DataMember]
    public int Id { get; set; }

    [DataMember]
    public string Value { get; set; }
}

public class TestApp
{
    public void Run()
    {
        IList<ITestObject> a = new List<ITestObject>();
        a.Add(new TestObject() { Id = 1, Value = "A" });
        a.Add(new TestObject() { Id = 2, Value = "B" });

        IList<ITestObject> b = Copy(a);

        // a is a List<T> while b is a readonly T[]
        Debug.WriteLine(a.GetType().FullName);
        Debug.WriteLine(b.GetType().FullName);
    }

    public IList<ITestObject> Copy(IList<ITestObject> list)
    {
        DataContractSerializer serializer = new DataContractSerializer(typeof(IList<ITestObject>), new Type[] { typeof(TestObject) });
        using (Stream stream = new MemoryStream())
        {
            serializer.WriteObject(stream, list);
            stream.Seek(0, SeekOrigin.Begin);
            IList<ITestObject> clone = (IList<ITestObject>)serializer.ReadObject(stream);
            stream.Close();
            return clone;
        }
    }
}

我猜这与事实List<T>没有列为KnownType

的事实有关。

1 个答案:

答案 0 :(得分:3)

尝试使用DataContractSerializer(typeof(List<ITestObject>)以便它知道具体类型