使用DataContractSerializer序列化从List <>继承的类不会序列化对象属性

问题描述 投票:0回答:1

由于当从List <>继承类时,XmlSerializer无法序列化任何其他属性,因此我尝试使用DataContractSerializer解决它们。这应该工作,如下所述:When a class is inherited from List<>, XmlSerializer doesn't serialize other attributes

但我得到了相同的结果。如果对象继承自List <>,则TestValue属性不会被序列化。

using System.Runtime.Serialization;

[Serializable]
public class XSerBase 
{
    [DataMember]
    public XSerTest XSerTest { get; set; } = new XSerTest();
}

[Serializable]
public class XSerTest : List<string>
{
    [DataMember]
    public string TestValue { get; set; }
}

{// my serialize / deserialize example

    XSerBase objectSource = new XSerBase();
    objectSource.XSerTest.TestValue = "QWERT";

    MemoryStream mem = new MemoryStream();
    DataContractSerializer dcsSource = new DataContractSerializer(typeof(XSerBase));
    dcsSource.WriteObject(mem, objectSource);
    mem.Position = 0;

    XSerBase objectDestination = null;
    DataContractSerializer dcsDestination = new DataContractSerializer(typeof(XSerBase));
    objectDestination = (dcsDestination.ReadObject(mem) as XSerBase);

    // objectDestination.XSerTest.TestValue is null
    // objectDestination.XSerTest.TestValue is "QWERT", when XSerTest is not inherited from List<string>

}

我错过了一个属性吗?

c# xml serialization xml-serialization datacontractserializer
1个回答
1
投票

我试图让一个继承的类List工作,但没有成功。这是我能做的最好的事情

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Globalization;
using System.Xml;
using System.Xml.Serialization;

namespace ConsoleApplication106
{

    class Program
    {
        const string FILENAME = @"c:\temp\test.xml";
        static void Main(string[] args)
        {
            XSerBase test = new XSerBase()
            {
                XSerTest = new List<XSerTest>() { 
                    new XSerTest() { TestValue = "123"},
                    new XSerTest() { TestValue = "456"}
                }
            };


            XmlSerializer serializer = new XmlSerializer(typeof(XSerBase));

            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;
            XmlWriter writer = XmlWriter.Create(FILENAME,settings);

            serializer.Serialize(writer, test);

            writer.Flush();
            writer.Close();

        }

    }
    public class XSerBase
    {
        [XmlElement("XSerTest")]
        public List<XSerTest> XSerTest { get; set; }
    }
    public class XSerTest
    {
        public string TestValue { get; set; } 
    }

}
© www.soinside.com 2019 - 2024. All rights reserved.