简体   繁体   English

如何反序列化列表 <T> 作为另一个列表 <T> 而不是只读的T []?

[英]How do I deserialize a List<T> as another List<T> instead of a readonly T[]?

We have some code that makes a copy of a List<T> of objects. 我们有一些代码可以复制对象的List<T> The problem is the code is returning a readonly array of T[] instead of a List<T> . 问题在于代码返回的是T[]的只读数组,而不是List<T>

Why is that, and how can I fix this deserialization code? 为什么会这样,如何解决此反序列化代码?

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;
        }
    }
}

I'm guessing it's something to do with the fact List<T> isn't listed as a KnownType 我想这与List<T>未列为KnownType的事实有关

尝试使用DataContractSerializer(typeof(List<ITestObject>) ,以使其了解具体类型

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM